1<?php 2 3namespace dokuwiki\Search\Index; 4 5/** 6 * Provides operations on tuple records used in our indexes 7 * 8 * Tuples consist of a key (typically a RID from another Index) and a number (usually a count). 9 * Used to store page <-> word counts for example 10 */ 11class TupleOps 12{ 13 /** 14 * Insert or replace a tuple in a line 15 * 16 * @param string $record This is the current row value to be modified 17 * @param int|string $key The foreign rid or identifier 18 * @param int $count The count to store 19 * @return string A new row value 20 * @author Tom N Harris <tnharris@whoopdedo.org> 21 * 22 */ 23 public static function updateTuple($record, $key, $count) 24 { 25 if ($record != '') { 26 // remove any current version of the tuple 27 $record = preg_replace('/(^|:)' . preg_quote($key, '/') . '\*\d*/', '', $record); 28 } 29 $record = trim($record, ':'); 30 if ($count) { 31 if ($record) { 32 return "{$key}*{$count}:" . $record; 33 } else { 34 return "{$key}*{$count}"; 35 } 36 } 37 return $record; 38 } 39 40 /** 41 * Sum the counts in a list of tuples 42 * 43 * @param string $record The row value to parse 44 * @return int sum of all counts 45 * @author Tom N Harris <tnharris@whoopdedo.org> 46 */ 47 public static function aggregateTupleCounts($record) 48 { 49 $freq = 0; 50 $parts = explode(':', $record); 51 foreach ($parts as $tuple) { 52 if ($tuple === '') continue; 53 list(/* $key */, $cnt) = explode('*', $tuple); 54 $freq += (int)$cnt; 55 } 56 return $freq; 57 } 58 59 /** 60 * Split a line into an array of tuples 61 * 62 * The given key of the given $filtermap defines which tuples to extract, the value 63 * gives the name in the output array. This basically allows to map RIDs to their 64 * respective real values. The result will contain the counts associated with the 65 * mapped keys. 66 * 67 * @param string $record The row value to parse 68 * @param array $filtermap Associative array of ($key => $mapping) 69 * @return array mapped counts 70 * @author Andreas Gohr <andi@splitbrain.org> 71 * 72 * @author Tom N Harris <tnharris@whoopdedo.org> 73 */ 74 public static function parseTuples($record, $filtermap) 75 { 76 $result = array(); 77 if ($record == '') return $result; 78 $parts = explode(':', $record); 79 foreach ($parts as $tuple) { 80 if ($tuple === '') continue; 81 list($key, $cnt) = explode('*', $tuple); 82 if (!$cnt) continue; 83 if (empty($filtermap[$key])) continue; 84 $mapped = $filtermap[$key]; 85 $result[$mapped] = $cnt; 86 } 87 return $result; 88 } 89} 90