-
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.php
More file actions
executable file
·110 lines (95 loc) · 2.47 KB
/
Copy pathindex.php
File metadata and controls
executable file
·110 lines (95 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<?php
/**
* Autoloader for all Kirby GEO Classes
*/
use Kirby\Cms\Collection;
use Kirby\Content\Field;
use Kirby\Exception\InvalidArgumentException;
use Kirby\Geo\Geo;
use Kirby\Geo\Point;
load([
'kirby\\geo\\geo' => __DIR__ . '/src/Geo.php',
'kirby\\geo\\point' => __DIR__ . '/src/Point.php'
]);
/**
* Creates a class alias for the GEO class, to make it more usable
*/
class_alias('Kirby\\Geo\\Geo', 'Geo');
/**
* Plugin Definition
*/
Kirby::plugin('getkirby/geo', [
'collectionFilters' => [
/**
* Adds a new radius filter to all collections
*/
'radius' => function (
Collection $collection,
string $field,
array $options
): Collection {
$origin = Geo::point($options['lat'] ?? null, $options['lng'] ?? null);
$radius = (int)($options['radius'] ?? null);
$unit = $options['unit'] ?? 'km' === 'km' ? 'km' : 'mi';
if ($radius === 0) {
throw new Exception('Invalid radius value for radius filter. You must specify a valid integer value');
}
foreach ($collection->data as $key => $item) {
$value = $collection->getAttribute($item, $field);
// skip invalid points
if (
is_string($value) === false &&
$value instanceof Field === false
) {
unset($collection->$key);
continue;
}
try {
$point = Geo::point((string)$value);
} catch (InvalidArgumentException) {
unset($collection->$key);
continue;
}
$distance = Geo::distance($origin, $point, $unit);
if ($distance > $radius) {
unset($collection->$key);
}
}
return $collection;
}
],
'fieldMethods' => [
/**
* Adds a new field method "coordinates",
* which can be used to convert a field with
* comma separated lat and long values to a Kirby Geo Point
*/
'coordinates' => function (Field $field): Point {
return Geo::point($field->value());
},
/**
* Adds a new field method "distance",
* which can be used to calculate the distance between a
* field with comma separated lat and long values and a
* valid Kirby Geo Point
*/
'distance' => function (
Field $field,
Point $point,
string $unit = 'km'
): float {
return Geo::distance($field->coordinates(), $point, $unit);
},
/**
* Same as distance, but will return a human readable version
* of the distance instead of a long float
*/
'niceDistance' => function (
Field $field,
Point $point,
string $unit = 'km'
): string {
return Geo::niceDistance($field->coordinates(), $point, $unit);
},
],
]);