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

JsonLdQuantityFormatter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 95%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 5
c 3
b 0
f 1
lcom 1
cbo 4
dl 0
loc 54
ccs 19
cts 20
cp 0.95
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 1
A format() 0 7 2
A toJsonLd() 0 14 2
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