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

CachedJsonLdDataValueFormatter   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 88.89%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 4
c 1
b 0
f 1
lcom 1
cbo 2
dl 0
loc 35
ccs 8
cts 9
cp 0.8889
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A format() 0 13 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