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

JsonLdGlobeCoordinateFormatter   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 38.1%

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 8
cts 21
cp 0.381
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A format() 0 7 2
A toJsonLd() 0 8 1
A roundDegrees() 0 11 3
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
		parent::__construct($options);
32
	}
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
		return $this->toJsonLd($value);
43
	}
44
45 1
	private function toJsonLd(GlobeCoordinateValue $value) {
46
		$resource = new stdClass();
47 1
		$resource->{'@type'} = 'GeoCoordinates';
48
		$resource->name = $this->globeCoordinateFormatter->format($value);
49
		$resource->latitude = $this->roundDegrees($value->getLatitude(), $value->getPrecision());
50
		$resource->longitude = $this->roundDegrees($value->getLongitude(), $value->getPrecision());
51 1
		return $resource;
52 1
	}
53
54
	/**
55
	 * copy of GeoCoordinateFormatter::roundDegrees
56
	 */
57
	private function roundDegrees($degrees, $precision) {
58
		if($precision <= 0) {
59
			$precision = 1 / 3600;
60
		}
61
62
		$sign = $degrees > 0 ? 1 : -1;
63
		$reduced = round(abs($degrees) / $precision);
64
		$expanded = $reduced * $precision;
65
66
		return $sign * $expanded;
67
	}
68
}
69