EntityIdForTermCache   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 70
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 95.45%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 7
c 1
b 0
f 0
lcom 1
cbo 2
dl 0
loc 70
ccs 21
cts 22
cp 0.9545
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A contains() 0 3 1
A getCacheId() 0 4 1
A fetch() 0 9 2
A save() 0 9 2
1
<?php
2
3
namespace Wikibase\EntityStore\Cache;
4
5
use Doctrine\Common\Cache\Cache;
6
use OutOfBoundsException;
7
use RuntimeException;
8
use Wikibase\DataModel\Entity\EntityId;
9
use Wikibase\DataModel\Term\Term;
10
11
/**
12
 * @licence GPLv2+
13
 * @author Thomas Pellissier Tanon
14
 */
15
class EntityIdForTermCache {
16
17
	const CACHE_ID_PREFIX = 'wikibase-store-entityforterm-';
18
19
	const CACHE_LIFE_TIME = 86400;
20
21
	/**
22
	 * @var Cache
23
	 */
24
	private $cache;
25
26
	/**
27
	 * @var int
28
	 */
29
	private $lifeTime;
30
31
	/**
32
	 * @param Cache $cache
33
	 * @param int $lifeTime
34
	 */
35 5
	public function __construct( Cache $cache, $lifeTime = 0 ) {
36 5
		$this->cache = $cache;
37 5
		$this->lifeTime = $lifeTime;
38 5
	}
39
40
	/**
41
	 * @param Term $term
42
	 * @param string $entityType
43
	 * @return EntityId[]
44
	 * @throws OutOfBoundsException
45
	 */
46 3
	public function fetch( Term $term, $entityType ) {
47 3
		$result = $this->cache->fetch( $this->getCacheId( $term, $entityType ) );
48
49 3
		if( $result === false ) {
50 2
			throw new OutOfBoundsException( 'The search is not in the cache.' );
51
		}
52
53 1
		return $result;
54
	}
55
56
	/**
57
	 * @param Term $term
58
	 * @param string $entityType
59
	 * @return boolean
60
	 */
61 2
	public function contains( Term $term, $entityType ) {
62 2
		return $this->cache->contains( $this->getCacheId( $term, $entityType ) );
63
	}
64
65
	/**
66
	 * @param Term $term
67
	 * @param string $entityType
68
	 * @param EntityId[] $entities
69
	 */
70 3
	public function save( Term $term, $entityType, array $entities ) {
71 3
		if( !$this->cache->save(
72 3
			$this->getCacheId( $term, $entityType ),
73 3
			$entities,
74 3
			$this->lifeTime
75 3
		) ) {
76
			throw new RuntimeException( 'The cache failed to save.' );
77
		}
78 3
	}
79
80 5
	private function getCacheId( Term $term, $entityType ) {
81 5
		return self::CACHE_ID_PREFIX . WIKIBASE_DATAMODEL_VERSION . '-' .
82 5
			$entityType . '-' . $term->getLanguageCode() . '-' . hash( 'md5', $term->getText() );
83
	}
84
}
85