Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
95.65% |
22 / 23 |
|
50.00% |
1 / 2 |
CRAP | |
0.00% |
0 / 1 |
| MediaSearchCachingEntitiesFetcher | |
95.65% |
22 / 23 |
|
50.00% |
1 / 2 |
3 | |
0.00% |
0 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| get | |
95.45% |
21 / 22 |
|
0.00% |
0 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | namespace Wikibase\MediaInfo\Search; |
| 4 | |
| 5 | use Wikimedia\ObjectCache\WANObjectCache; |
| 6 | |
| 7 | class MediaSearchCachingEntitiesFetcher extends MediaSearchEntitiesFetcher { |
| 8 | public function __construct( |
| 9 | protected readonly MediaSearchEntitiesFetcher $fetcher, |
| 10 | protected readonly WANObjectCache $objectCache, |
| 11 | protected readonly string $inputLanguage, |
| 12 | protected readonly string $outputLanguage, |
| 13 | protected readonly string $queryKeyspace = '*', |
| 14 | protected readonly int $ttl = WANObjectCache::TTL_DAY, |
| 15 | ) { |
| 16 | } |
| 17 | |
| 18 | /** |
| 19 | * This is a wrapper around another MediaSearchEntitiesFetcher where the actual data is |
| 20 | * fetched. |
| 21 | * This simply reads from/writes to an intermediate cache in a separate key-value store, for |
| 22 | * follow-up requests (e.g. loading next batch of results for the same term) |
| 23 | * |
| 24 | * @param array $searchQueries |
| 25 | * @return array |
| 26 | */ |
| 27 | public function get( array $searchQueries ): array { |
| 28 | if ( count( $searchQueries ) === 0 ) { |
| 29 | return []; |
| 30 | } |
| 31 | |
| 32 | $cacheKeys = $this->objectCache->makeMultiKeys( |
| 33 | $searchQueries, |
| 34 | function ( $query ) { |
| 35 | return $this->objectCache->makeKey( |
| 36 | 'wbmi-mediasearch-entities', |
| 37 | $this->queryKeyspace, |
| 38 | $query, |
| 39 | $this->inputLanguage, |
| 40 | $this->outputLanguage |
| 41 | ); |
| 42 | } |
| 43 | ); |
| 44 | |
| 45 | // lookup in key/value store & fall back to actual fetch when it can't be found |
| 46 | $cacheResult = $this->objectCache->getMultiWithUnionSetCallback( |
| 47 | $cacheKeys, |
| 48 | $this->ttl, |
| 49 | function ( array $queries ) { |
| 50 | return $this->fetcher->get( $queries ); |
| 51 | } |
| 52 | ); |
| 53 | |
| 54 | // $cacheResult is associative array with cache keys, but we want keys to be the |
| 55 | // search queries; objectcache preserves key order, so a simple combine is safe |
| 56 | return array_combine( $searchQueries, $cacheResult ); |
| 57 | } |
| 58 | } |