DispatchingJsonLdDataValueFormatter::format()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 15
ccs 0
cts 9
cp 0
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 1
crap 12
1
<?php
2
3
namespace PPP\Wikidata\ValueFormatters\JsonLd;
4
5
use DataValues\DataValue;
6
use InvalidArgumentException;
7
use ValueFormatters\FormatterOptions;
8
use ValueFormatters\FormattingException;
9
use ValueFormatters\ValueFormatterBase;
10
11
/**
12
 * Choose the right formatter for the given type and return the formatted value.
13
 *
14
 * @licence AGPLv3+
15
 * @author Thomas Pellissier Tanon
16
 */
17
class DispatchingJsonLdDataValueFormatter extends ValueFormatterBase implements JsonLdDataValueFormatter {
18
19
	/**
20
	 * @var JsonLdDataValueFormatter[]
21
	 */
22
	public $formatters;
23
24
	/**
25
	 * @param JsonLdDataValueFormatter[] $formatters
26
	 * @param FormatterOptions $options
27
	 */
28
	public function __construct(array $formatters, FormatterOptions $options) {
29
		$this->formatters = $formatters;
30
31
		parent::__construct($options);
32
	}
33
34
	/**
35
	 * @see ValueFormatter::format
36
	 */
37
	public function format($value) {
38
		if(!($value instanceof DataValue)) {
39
			throw new InvalidArgumentException('$value should be a DataValue');
40
		}
41
42
		$type = $value->getType();
43
44
		if(!array_key_exists($type, $this->formatters)) {
45
			throw new FormattingException(
46
				$type . ' is not one of the type supported by the value formatter (' . implode(', ', array_keys($this->formatters)) . ')'
47
			);
48
		}
49
50
		return $this->formatters[$type]->format($value);
51
	}
52
}
53