|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace frictionlessdata\tableschema\Fields; |
|
4
|
|
|
|
|
5
|
|
|
class GeopointField extends BaseField |
|
6
|
|
|
{ |
|
7
|
|
|
protected function validateCastValue($val) |
|
8
|
|
|
{ |
|
9
|
|
|
if (in_array($this->format(), ['array', 'object']) && is_string($val)) { |
|
10
|
|
|
try { |
|
11
|
|
|
$val = json_decode($val); |
|
12
|
|
|
} catch (\Exception $e) { |
|
13
|
|
|
throw $this->getValidationException($e->getMessage(), $val); |
|
14
|
|
|
} |
|
15
|
|
|
} |
|
16
|
|
|
switch ($this->format()) { |
|
17
|
|
|
case 'default': |
|
|
|
|
|
|
18
|
|
|
if (!is_string($val)) { |
|
19
|
|
|
throw $this->getValidationException('value must be a string', $val); |
|
20
|
|
|
} else { |
|
21
|
|
|
$val = explode(',', $val); |
|
22
|
|
|
if (count($val) != 2) { |
|
23
|
|
|
throw $this->getValidationException('value must be a string with 2 comma-separated elements', $val); |
|
24
|
|
|
} else { |
|
25
|
|
|
return $this->getNativeGeopoint($val); |
|
26
|
|
|
} |
|
27
|
|
|
} |
|
28
|
|
|
case 'array': |
|
|
|
|
|
|
29
|
|
|
if (!is_array($val) || array_keys($val) != [0, 1]) { |
|
30
|
|
|
throw $this->getValidationException('value must be an array with 2 elements', $val); |
|
31
|
|
|
} else { |
|
32
|
|
|
return $this->getNativeGeopoint($val); |
|
33
|
|
|
} |
|
34
|
|
|
case 'object': |
|
|
|
|
|
|
35
|
|
|
$val = json_decode(json_encode($val), true); |
|
36
|
|
|
if (!is_array($val) || !array_key_exists('lat', $val) || !array_key_exists('lon', $val)) { |
|
37
|
|
|
throw $this->getValidationException('object must contain lon and lat attributes', $val); |
|
38
|
|
|
} else { |
|
39
|
|
|
return $this->getNativeGeopoint([$val['lon'], $val['lat']]); |
|
40
|
|
|
} |
|
41
|
|
|
default: |
|
42
|
|
|
throw $this->getValidationException('invalid format', $val); |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
public static function type() |
|
47
|
|
|
{ |
|
48
|
|
|
return 'geopoint'; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
protected function getNativeGeopoint($arr) |
|
52
|
|
|
{ |
|
53
|
|
|
list($lon, $lat) = $arr; |
|
54
|
|
|
$lon = (int) $lon; |
|
55
|
|
|
$lat = (int) $lat; |
|
56
|
|
|
if ( |
|
57
|
|
|
$lon > 180 || $lon < -180 |
|
58
|
|
|
|| $lat > 90 or $lat < -90 |
|
|
|
|
|
|
59
|
|
|
) { |
|
60
|
|
|
throw $this->getValidationException('invalid lon,lat values', json_encode($arr)); |
|
61
|
|
|
} else { |
|
62
|
|
|
return [$lon, $lat]; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
|
|
|