-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAlgoliaPlaces.php
240 lines (194 loc) · 7.08 KB
/
AlgoliaPlaces.php
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
<?php
declare(strict_types=1);
/*
* This file is part of the Geocoder package.
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @license MIT License
*/
namespace Geocoder\Provider\AlgoliaPlaces;
use Geocoder\Collection;
use Geocoder\Exception\InvalidArgument;
use Geocoder\Exception\UnsupportedOperation;
use Geocoder\Http\Provider\AbstractHttpProvider;
use Geocoder\Model\Address;
use Geocoder\Model\AddressBuilder;
use Geocoder\Model\AddressCollection;
use Geocoder\Provider\Provider;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\RequestInterface;
class AlgoliaPlaces extends AbstractHttpProvider implements Provider
{
public const TYPE_CITY = 'city';
public const TYPE_COUNTRY = 'country';
public const TYPE_ADDRESS = 'address';
public const TYPE_BUS_STOP = 'busStop';
public const TYPE_TRAIN_STATION = 'trainStation';
public const TYPE_TOWN_HALL = 'townhall';
public const TYPE_AIRPORT = 'airport';
/** @var string */
public const ENDPOINT_URL_SSL = 'https://places-dsn.algolia.net/1/places/query';
/** @var string */
private $apiKey;
/** @var string */
private $appId;
/** @var GeocodeQuery */
private $query;
public function __construct(ClientInterface $client, ?string $apiKey = null, ?string $appId = null)
{
parent::__construct($client);
$this->apiKey = $apiKey;
$this->appId = $appId;
}
public function getName(): string
{
return 'algolia_places';
}
public function geocodeQuery(GeocodeQuery $query): Collection
{
if (filter_var($query->getText(), FILTER_VALIDATE_IP)) {
throw new UnsupportedOperation('The AlgoliaPlaces provider does not support IP addresses, only street addresses.');
}
$this->query = $query;
$request = $this->getRequest(self::ENDPOINT_URL_SSL);
$jsonParsed = $this->getParsedResponse($request);
$jsonResponse = json_decode($jsonParsed, true);
if (is_null($jsonResponse)) {
return new AddressCollection([]);
}
if ($jsonResponse['degradedQuery']) {
return new AddressCollection([]);
}
if (0 === $jsonResponse['nbHits']) {
return new AddressCollection([]);
}
return $this->buildResult($jsonResponse, $query->getLocale());
}
public function reverseQuery(ReverseQuery $query): Collection
{
throw new UnsupportedOperation('The AlgoliaPlaces provided does not support reverse geocoding.');
}
/**
* @return string[]
*/
public function getTypes(): array
{
return [
self::TYPE_CITY,
self::TYPE_COUNTRY,
self::TYPE_ADDRESS,
self::TYPE_BUS_STOP,
self::TYPE_TRAIN_STATION,
self::TYPE_TOWN_HALL,
self::TYPE_AIRPORT,
];
}
protected function getRequest(string $url): RequestInterface
{
return $this->createRequest(
'POST',
$url,
$this->buildHeaders(),
$this->buildData()
);
}
private function buildData(): string
{
$query = $this->query;
$params = [
'query' => $query->getText(),
'aroundLatLngViaIP' => false,
'language' => $query->getLocale(),
'type' => $this->buildType($query),
'countries' => $this->buildCountries($query),
];
return json_encode(array_filter($params));
}
private function buildType(GeocodeQuery $query): string
{
$type = $query->getData('type', '');
if (!empty($type) && !in_array($type, $this->getTypes())) {
throw new InvalidArgument(sprintf('The type provided to AlgoliaPlace provider must be in `%s`', implode(', ', $this->getTypes())));
}
return $type;
}
/**
* @return string[]
*/
private function buildCountries(GeocodeQuery $query): array
{
return array_map(function (string $country) {
if (2 !== strlen($country)) {
throw new InvalidArgument('The country provided to AlgoliaPlace provider must be an ISO 639-1 code.');
}
return strtolower($country); // Country codes MUST be lower-cased
}, $query->getData('countries') ?? []);
}
/**
* @return array<string, string>
*/
private function buildHeaders(): array
{
if (empty($this->appId) || empty($this->apiKey)) {
return [];
}
return [
'X-Algolia-Application-Id' => $this->appId,
'X-Algolia-API-Key' => $this->apiKey,
];
}
/**
* @param array<string, mixed> $jsonResponse
*/
private function buildResult(array $jsonResponse, ?string $locale = null): AddressCollection
{
$results = [];
// 1. degradedQuery: checkfor if(degradedQuery) and set results accordingly?
// 2. setStreetNumber($result->locale_name) AlgoliaPlaces does not offer streetnumber
// precision for the geocoding (with the exception to addresses situated in France)
foreach ($jsonResponse['hits'] as $result) {
$builder = new AddressBuilder($this->getName());
$builder->setCoordinates($result['_geoloc']['lat'], $result['_geoloc']['lng']);
if (isset($result['country'])) {
$builder->setCountry($this->getResultAttribute($result, 'country', $locale));
}
$builder->setCountryCode($result['country_code']);
if (isset($result['city'])) {
$builder->setLocality($this->getResultAttribute($result, 'city', $locale));
}
if (isset($result['postcode'])) {
$builder->setPostalCode($result['postcode'][0]);
}
if (isset($result['locale_name'])) {
$builder->setStreetNumber($result['locale_name']);
}
if (isset($result['locale_names']) && isset($result['locale_names'][0])) {
$builder->setStreetName($this->getResultAttribute($result, 'locale_names', $locale));
}
foreach ($result['administrative'] ?? [] as $i => $adminLevel) {
$builder->addAdminLevel($i + 1, $adminLevel[0]);
}
$results[] = $builder->build(Address::class);
}
return new AddressCollection($results);
}
/**
* When no locale was set in the query, Algolia will return results for all locales.
* In this case, we return the default locale value.
*
* @param array<string, mixed> $result
*
* @return string|int|float
*/
private function getResultAttribute(array $result, string $attribute, ?string $locale = null)
{
if (!is_array($result[$attribute])) {
return $result[$attribute];
}
$value = null !== $locale ? $result[$attribute] : $result[$attribute]['default'];
return is_array($value) ? $value[0] : $value;
}
}