Completed
Push — master ( 2a3272...f39d74 )
by Thomas
08:55
created

CachedJsonLdDataValueFormatter::__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\ValueFormatters;
4
5
use DataValues\DataValue;
6
use InvalidArgumentException;
7
use OutOfBoundsException;
8
use PPP\Wikidata\Cache\JsonLdDataValueFormatterCache;
9
use PPP\Wikidata\ValueFormatters\JsonLd\JsonLdDataValueFormatter;
10
11
/**
12
 * Adds a cache level on top of JsonLdDataValueFormatter
13
 *
14
 * @licence GPLv2+
15
 * @author Thomas Pellissier Tanon
16
 */
17
class CachedJsonLdDataValueFormatter implements JsonLdDataValueFormatter {
18
19
	/**
20
	 * @var JsonLdDataValueFormatter
21
	 */
22
	private $formatter;
23
24
	/**
25
	 * @var JsonLdDataValueFormatterCache
26
	 */
27
	private $cache;
28
29
30 2
	public function __construct(JsonLdDataValueFormatter $formatter, JsonLdDataValueFormatterCache $cache) {
31 2
		$this->formatter = $formatter;
32 2
		$this->cache = $cache;
33
	}
34
35
	/**
36
	 * @see ValueFormatter::format
37
	 */
38 2
	public function format($value) {
39 2
		if(!($value instanceof DataValue)) {
40
			throw new InvalidArgumentException('$value is not a DataValue.');
41
		}
42
43
		try {
44 1
			return $this->cache->fetch($value);
45
		} catch(OutOfBoundsException $e) {
46
			$jsonLd = $this->formatter->format($value);
47
			$this->cache->save($value, $jsonLd);
48 1
			return $jsonLd;
49 1
		}
50
	}
51
}
52