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

JsonLdQuantityFormatter   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 50%

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 9
cts 18
cp 0.5
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
		parent::__construct($options);
42
	}
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
		return $this->toJsonLd($value);
53
	}
54
55 2
	private function toJsonLd(QuantityValue $value) {
56
		$resource = new stdClass();
57 2
		$resource->{'@type'} = 'QuantitativeValue';
58
		$resource->name = $this->quantityFormatter->format($value);
59
		$resource->value = $this->decimalFormatter->format($value->getAmount());
60
		$resource->minValue = $this->decimalFormatter->format($value->getLowerBound());
61
		$resource->maxValue = $this->decimalFormatter->format($value->getUpperBound());
62
63
		if($value->getUnit() !== '1') {
64
			$resource->unitCode = $value->getUnit();
65
		}
66
67 2
		return $resource;
68 2
	}
69
}
70