Completed
Push — master ( 7880aa...3f359c )
by Thomas
05:14
created

JsonLdDataValueFormatterCache::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1.0156

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 3
cts 4
cp 0.75
rs 10
cc 1
eloc 3
nc 1
nop 2
crap 1.0156
1
<?php
2
3
namespace PPP\Wikidata\Cache;
4
5
use DataValues\DataValue;
6
use Doctrine\Common\Cache\Cache;
7
use OutOfBoundsException;
8
use RuntimeException;
9
use stdClass;
10
11
/**
12
 * Cache whose keys are based on SiteLink
13
 *
14
 * @licence GPLv2+
15
 * @author Thomas Pellissier Tanon
16
 */
17
class JsonLdDataValueFormatterCache {
18
19
	const CACHE_ID_PREFIX = 'ppp-wd-jsonld-dv-';
20
21
	const CACHE_LIFE_TIME = 86400;
22
23
	/**
24
	 * @var Cache
25
	 */
26
	private $cache;
27
28
	/**
29
	 * @var string
30
	 */
31
	private $name;
32
33
	/**
34
	 * @param Cache $cache
35
	 */
36 3
	public function __construct(Cache $cache, $name) {
37 3
		$this->cache = $cache;
38 3
		$this->name = $name;
39
	}
40
41
	/**
42
	 * @param DataValue $dataValue
43
	 * @return stdClass
44
	 */
45 2
	public function fetch(DataValue $dataValue) {
46
		$result = $this->cache->fetch($this->getCacheId($dataValue));
47
48 2
		if($result === false) {
49
			throw new OutOfBoundsException('The search is not in the cache.');
50
		}
51
52 1
		return $result;
53 2
	}
54
55
	/**
56
	 * @param DataValue $dataValue
57
	 * @return bool
58
	 */
59 2
	public function contains(DataValue $dataValue) {
60
		return $this->cache->contains($this->getCacheId($dataValue));
61 2
	}
62
63
	/**
64
	 * @param DataValue $dataValue
65
	 * @param stdClass $jsonLd
66
	 */
67 3
	public function save(DataValue $dataValue, stdClass $jsonLd) {
68 3
		if(!$this->cache->save(
69 3
			$this->getCacheId($dataValue),
70
			$jsonLd,
71 3
			self::CACHE_LIFE_TIME
72
		)) {
73
			throw new RuntimeException('The cache failed to save.');
74
		}
75
	}
76
77 1
	private function getCacheId(DataValue $dataValue) {
78
		return self::CACHE_ID_PREFIX . '-' . $this->name . '-' . $dataValue->getHash();
79 1
	}
80
}
81