| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
namespace Wikimedia\DependencyStore; |
| 22 |
|
| 23 |
use InvalidArgumentException; |
| 24 |
use Wikimedia\ObjectCache\BagOStuff; |
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
class KeyValueDependencyStore extends DependencyStore { |
| 34 |
|
| 35 |
private $stash; |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
public function __construct( BagOStuff $stash ) { |
| 41 |
$this->stash = $stash; |
| 42 |
} |
| 43 |
|
| 44 |
public function retrieveMulti( $type, array $entities ) { |
| 45 |
$entitiesByKey = []; |
| 46 |
foreach ( $entities as $entity ) { |
| 47 |
$entitiesByKey[$this->getStoreKey( $type, $entity )] = $entity; |
| 48 |
} |
| 49 |
|
| 50 |
$blobsByKey = $this->stash->getMulti( array_keys( $entitiesByKey ) ); |
| 51 |
|
| 52 |
$results = []; |
| 53 |
foreach ( $entitiesByKey as $key => $entity ) { |
| 54 |
$blob = $blobsByKey[$key] ?? null; |
| 55 |
$data = is_string( $blob ) ? json_decode( $blob, true ) : null; |
| 56 |
$results[$entity] = $this->newEntityDependencies( |
| 57 |
$data[self::KEY_PATHS] ?? [], |
| 58 |
$data[self::KEY_AS_OF] ?? null |
| 59 |
); |
| 60 |
} |
| 61 |
|
| 62 |
return $results; |
| 63 |
} |
| 64 |
|
| 65 |
public function storeMulti( $type, array $dataByEntity, $ttl ) { |
| 66 |
$blobsByKey = []; |
| 67 |
foreach ( $dataByEntity as $entity => $data ) { |
| 68 |
if ( !is_array( $data[self::KEY_PATHS] ) || !is_int( $data[self::KEY_AS_OF] ) ) { |
| 69 |
throw new InvalidArgumentException( "Invalid entry for '$entity'" ); |
| 70 |
} |
| 71 |
|
| 72 |
|
| 73 |
$data[self::KEY_PATHS] = array_values( array_unique( $data[self::KEY_PATHS] ) ); |
| 74 |
sort( $data[self::KEY_PATHS], SORT_STRING ); |
| 75 |
|
| 76 |
$blob = json_encode( $data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE ); |
| 77 |
$blobsByKey[$this->getStoreKey( $type, $entity )] = $blob; |
| 78 |
} |
| 79 |
|
| 80 |
if ( $blobsByKey ) { |
| 81 |
$this->stash->setMulti( $blobsByKey, $ttl, BagOStuff::WRITE_BACKGROUND ); |
| 82 |
} |
| 83 |
} |
| 84 |
|
| 85 |
public function remove( $type, $entities ) { |
| 86 |
$keys = []; |
| 87 |
foreach ( (array)$entities as $entity ) { |
| 88 |
$keys[] = $this->getStoreKey( $type, $entity ); |
| 89 |
} |
| 90 |
|
| 91 |
if ( $keys ) { |
| 92 |
$this->stash->deleteMulti( $keys, BagOStuff::WRITE_BACKGROUND ); |
| 93 |
} |
| 94 |
} |
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
private function getStoreKey( $type, $entity ) { |
| 102 |
return $this->stash->makeKey( "{$type}-dependencies", $entity ); |
| 103 |
} |
| 104 |
} |