Completed
Push — master ( ac7e0a...7880aa )
by Thomas
04:53
created

JsonLdQuantityFormatter::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 7
nc 1
nop 3
crap 1
1
<?php
2
3
namespace PPP\Wikidata\ValueFormatters\JsonLd;
4
5
use DataValues\QuantityValue;
6
use InvalidArgumentException;
7
use stdClass;
8
use ValueFormatters\FormatterOptions;
9
use ValueFormatters\QuantityFormatter;
10
use ValueFormatters\ValueFormatterBase;
11
12
/**
13
 * @licence GPLv2+
14
 * @author Thomas Pellissier Tanon
15
 */
16
class JsonLdQuantityFormatter extends ValueFormatterBase implements JsonLdDataValueFormatter {
17
18
	/**
19
	 * @var QuantityFormatter
20
	 */
21
	private $quantityFormatter;
22
23
	/**
24
	 * @var JsonLdDecimalFormatter
25
	 */
26
	private $decimalFormatter;
27
28
	/**
29
	 * @param QuantityFormatter $quantityFormatter
30
	 * @param JsonLdDecimalFormatter $decimalFormatter
31
	 * @param FormatterOptions|null $options
32
	 */
33 2
	public function __construct(
34
		QuantityFormatter $quantityFormatter,
35
		JsonLdDecimalFormatter $decimalFormatter,
36
		FormatterOptions $options = null
37
	) {
38 2
		$this->quantityFormatter = $quantityFormatter;
39 2
		$this->decimalFormatter = $decimalFormatter;
40
41 2
		parent::__construct($options);
42 2
	}
43
44
	/**
45
	 * @see ValueFormatter::format
46
	 */
47 2
	public function format($value) {
48 2
		if(!($value instanceof QuantityValue)) {
49
			throw new InvalidArgumentException('$value is not a QuantityValue.');
50
		}
51
52 2
		return $this->toJsonLd($value);
53
	}
54
55 2
	private function toJsonLd(QuantityValue $value) {
56 2
		$resource = new stdClass();
57 2
		$resource->{'@type'} = 'QuantitativeValue';
58 2
		$resource->name = $this->quantityFormatter->format($value);
59 2
		$resource->value = $this->decimalFormatter->format($value->getAmount());
60 2
		$resource->minValue = $this->decimalFormatter->format($value->getLowerBound());
61 2
		$resource->maxValue = $this->decimalFormatter->format($value->getUpperBound());
62
63 2
		if($value->getUnit() !== '1') {
64 1
			$resource->unitCode = $value->getUnit();
65 1
		}
66
67 2
		return $resource;
68
	}
69
}
70