| 1 | <?php |
| 2 | |
| 3 | /** |
| 4 | * Trait useful for SearchResultSet implementations. |
| 5 | * It holds the functions that are rarely needed to be overridden. |
| 6 | * |
| 7 | * This trait can be used directly by extensions providing a SearchEngine. |
| 8 | * |
| 9 | * @ingroup Search |
| 10 | * @phan-file-suppress PhanUndeclaredMethod |
| 11 | */ |
| 12 | trait SearchResultSetTrait { |
| 13 | /** |
| 14 | * Set of result's extra data, indexed per result id |
| 15 | * and then per data item name. |
| 16 | * The structure is: |
| 17 | * PAGE_ID => [ augmentor name => data, ... ] |
| 18 | * @var array[] |
| 19 | */ |
| 20 | private $extraData = []; |
| 21 | |
| 22 | /** |
| 23 | * Sets augmented data for result set. |
| 24 | * @param string $name Extra data item name |
| 25 | * @param array[] $data Extra data as PAGEID => data |
| 26 | */ |
| 27 | public function setAugmentedData( $name, $data ) { |
| 28 | foreach ( $data as $id => $resultData ) { |
| 29 | $this->extraData[$id][$name] = $resultData; |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * Returns extra data for specific result and store it in SearchResult object. |
| 35 | * @param SearchResult $result |
| 36 | */ |
| 37 | public function augmentResult( SearchResult $result ) { |
| 38 | $id = $result->getTitle()->getArticleID(); |
| 39 | if ( $id === -1 ) { |
| 40 | return; |
| 41 | } |
| 42 | $result->setExtensionData( function () use ( $id ) { |
| 43 | return $this->extraData[$id] ?? []; |
| 44 | } ); |
| 45 | } |
| 46 | |
| 47 | /** |
| 48 | * @return int|null The offset the current page starts at. Typically |
| 49 | * this should be null to allow the UI to decide on its own, but in |
| 50 | * special cases like interleaved AB tests specifying explicitly is |
| 51 | * necessary. |
| 52 | */ |
| 53 | public function getOffset() { |
| 54 | return null; |
| 55 | } |
| 56 | |
| 57 | final public function getIterator(): ArrayIterator { |
| 58 | return new ArrayIterator( $this->extractResults() ); |
| 59 | } |
| 60 | } |