|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Wikibase\EntityStore\Cache; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\Common\Cache\Cache; |
|
6
|
|
|
use RuntimeException; |
|
7
|
|
|
use Wikibase\DataModel\Entity\EntityDocument; |
|
8
|
|
|
use Wikibase\DataModel\Entity\EntityId; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Cache of Entity objects. |
|
12
|
|
|
* |
|
13
|
|
|
* @licence GPLv2+ |
|
14
|
|
|
* @author Thomas Pellissier Tanon |
|
15
|
|
|
*/ |
|
16
|
|
|
class EntityDocumentCache { |
|
17
|
|
|
|
|
18
|
|
|
const CACHE_ID_PREFIX = 'wikibase-store-entity-'; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @var Cache |
|
22
|
|
|
*/ |
|
23
|
|
|
private $cache; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* @var int |
|
27
|
|
|
*/ |
|
28
|
|
|
private $lifeTime; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* @param Cache $cache |
|
32
|
|
|
* @param int $lifeTime |
|
33
|
|
|
*/ |
|
34
|
5 |
|
public function __construct( Cache $cache, $lifeTime = 0 ) { |
|
35
|
5 |
|
$this->cache = $cache; |
|
36
|
5 |
|
$this->lifeTime = $lifeTime; |
|
37
|
5 |
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Returns an Entity from the cache |
|
41
|
|
|
* |
|
42
|
|
|
* @param EntityId $entityId |
|
43
|
|
|
* @return EntityDocument|null |
|
44
|
|
|
*/ |
|
45
|
3 |
|
public function fetch( EntityId $entityId ) { |
|
46
|
3 |
|
return $this->cache->fetch( $this->getCacheIdFromEntityId( $entityId ) ) ?: null; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Tests if an Entity exists in the cache. |
|
51
|
|
|
* |
|
52
|
|
|
* @param EntityId $entityId |
|
53
|
|
|
* @return bool |
|
54
|
|
|
*/ |
|
55
|
2 |
|
public function contains( $entityId ) { |
|
56
|
2 |
|
return $this->cache->contains( $this->getCacheIdFromEntityId( $entityId ) ); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
/** |
|
60
|
|
|
* Save an Entity in the cache. |
|
61
|
|
|
* |
|
62
|
|
|
* @param EntityDocument $entity |
|
63
|
|
|
*/ |
|
64
|
3 |
|
public function save( EntityDocument $entity ) { |
|
65
|
3 |
|
if( !$this->cache->save( |
|
66
|
3 |
|
$this->getCacheIdFromEntityId( $entity->getId() ), |
|
|
|
|
|
|
67
|
3 |
|
$entity, |
|
68
|
3 |
|
$this->lifeTime |
|
69
|
3 |
|
) ) { |
|
70
|
|
|
throw new RuntimeException( 'The cache failed to save for entity ' . $entity->getId()->getSerialization() ); |
|
71
|
|
|
} |
|
72
|
3 |
|
} |
|
73
|
|
|
|
|
74
|
5 |
|
private function getCacheIdFromEntityId( EntityId $entityId ) { |
|
75
|
5 |
|
return self::CACHE_ID_PREFIX . WIKIBASE_DATAMODEL_VERSION . '-' . $entityId->getSerialization(); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|
Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code: