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
|
|
|
|