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

CachedJsonLdDataValueFormatter::format()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 13
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
eloc 9
nc 3
nop 1
crap 3
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