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