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

JsonLdGlobeCoordinateFormatter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 86.96%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 7
c 3
b 0
f 0
lcom 1
cbo 3
dl 0
loc 52
ccs 20
cts 23
cp 0.8696
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A toJsonLd() 0 8 1
A roundDegrees() 0 11 3
A format() 0 7 2
1
<?php
2
3
namespace PPP\Wikidata\ValueFormatters\JsonLd;
4
5
use DataValues\Geo\Formatters\GlobeCoordinateFormatter;
6
use DataValues\Geo\Values\GlobeCoordinateValue;
7
use InvalidArgumentException;
8
use stdClass;
9
use ValueFormatters\FormatterOptions;
10
use ValueFormatters\ValueFormatterBase;
11
12
/**
13
 * @licence GPLv2+
14
 * @author Thomas Pellissier Tanon
15
 * @todo support globes
16
 */
17
class JsonLdGlobeCoordinateFormatter extends ValueFormatterBase implements JsonLdDataValueFormatter {
18
19
	/**
20
	 * @var GlobeCoordinateFormatter
21
	 */
22
	private $globeCoordinateFormatter;
23
24
	/**
25
	 * @param GlobeCoordinateFormatter $globeCoordinateFormatter
26
	 * @param FormatterOptions|null $options
27
	 */
28 1
	public function __construct(GlobeCoordinateFormatter $globeCoordinateFormatter, FormatterOptions $options = null) {
29 1
		$this->globeCoordinateFormatter = $globeCoordinateFormatter;
30
31 1
		parent::__construct($options);
32 1
	}
33
34
	/**
35
	 * @see ValueFormatter::format
36
	 */
37 1
	public function format($value) {
38 1
		if(!($value instanceof GlobeCoordinateValue)) {
39
			throw new InvalidArgumentException('$value is not a GlobeCoordinateValue.');
40
		}
41
42 1
		return $this->toJsonLd($value);
43
	}
44
45 1
	private function toJsonLd(GlobeCoordinateValue $value) {
46 1
		$resource = new stdClass();
47 1
		$resource->{'@type'} = 'GeoCoordinates';
48 1
		$resource->name = $this->globeCoordinateFormatter->format($value);
49 1
		$resource->latitude = $this->roundDegrees($value->getLatitude(), $value->getPrecision());
50 1
		$resource->longitude = $this->roundDegrees($value->getLongitude(), $value->getPrecision());
51 1
		return $resource;
52
	}
53
54
	/**
55
	 * copy of GeoCoordinateFormatter::roundDegrees
56
	 */
57 1
	private function roundDegrees($degrees, $precision) {
58 1
		if($precision <= 0) {
59
			$precision = 1 / 3600;
60
		}
61
62 1
		$sign = $degrees > 0 ? 1 : -1;
63 1
		$reduced = round(abs($degrees) / $precision);
64 1
		$expanded = $reduced * $precision;
65
66 1
		return $sign * $expanded;
67
	}
68
}
69