-
Notifications
You must be signed in to change notification settings - Fork 520
Expand file tree
/
Copy pathIp2Geo.php
More file actions
162 lines (129 loc) · 5.79 KB
/
Ip2Geo.php
File metadata and controls
162 lines (129 loc) · 5.79 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
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
<?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\Ip2Geo;
use Geocoder\Collection;
use Geocoder\Exception\InvalidCredentials;
use Geocoder\Exception\InvalidServerResponse;
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;
final class Ip2Geo extends AbstractHttpProvider implements Provider
{
private const BASE_URL = 'https://api.ip2geo.dev';
private string $apiKey;
public function __construct(ClientInterface $client, string $apiKey)
{
if ('' === $apiKey) {
throw new InvalidCredentials('An API key is required.');
}
$this->apiKey = $apiKey;
parent::__construct($client);
}
public function geocodeQuery(GeocodeQuery $query): Collection
{
$address = $query->getText();
if (!filter_var($address, FILTER_VALIDATE_IP)) {
throw new UnsupportedOperation('The ip2geo provider does not support street addresses, only IP addresses.');
}
if (in_array($address, ['127.0.0.1', '::1', '0.0.0.0'], true)) {
return new AddressCollection([Address::createFromArray([])]);
}
$url = sprintf('%s/convert?ip=%s', self::BASE_URL, $address);
$request = $this->getRequest($url);
$request = $request->withHeader('X-Api-Key', $this->apiKey);
$content = $this->getParsedResponse($request);
$json = json_decode($content, true);
if (!is_array($json) || !isset($json['success'])) {
throw new InvalidServerResponse(sprintf('Could not decode response from ip2geo for IP "%s".', $address));
}
if (true !== $json['success'] || !isset($json['data'])) {
return new AddressCollection([]);
}
$data = $json['data'];
return $this->buildResult($data);
}
public function reverseQuery(ReverseQuery $query): Collection
{
throw new UnsupportedOperation('The ip2geo provider is not able to do reverse geocoding.');
}
public function getName(): string
{
return 'ip2geo';
}
private function buildResult(array $data): AddressCollection
{
$builder = new AddressBuilder($this->getName());
$continent = $data['continent'] ?? [];
$country = $continent['country'] ?? [];
$subdivision = $country['subdivision'] ?? [];
$city = $country['city'] ?? [];
$timezone = $city['timezone'] ?? [];
$flag = $country['flag'] ?? [];
$currency = $country['currency'] ?? [];
$asn = $data['asn'] ?? [];
$registeredCountry = $data['registered_country'] ?? [];
// Standard geocoder fields
if (isset($city['latitude'], $city['longitude'])) {
$builder->setCoordinates((float) $city['latitude'], (float) $city['longitude']);
}
if (isset($city['name'])) {
$builder->setLocality($city['name']);
}
if (isset($city['postal_code'])) {
$builder->setPostalCode($city['postal_code']);
}
if (isset($subdivision['name'], $subdivision['code'])) {
$builder->addAdminLevel(1, $subdivision['name'], $subdivision['code']);
}
if (isset($country['name'], $country['code'])) {
$builder->setCountry($country['name']);
$builder->setCountryCode($country['code']);
}
if (isset($timezone['name'])) {
$builder->setTimezone($timezone['name']);
}
// Build custom address with extra ip2geo fields
/** @var Ip2GeoAddress $address */
$address = $builder->build(Ip2GeoAddress::class);
$address = $address
->withIp($data['ip'] ?? null)
->withIpType($data['type'] ?? null)
->withIsEu($data['is_eu'] ?? null)
->withContinentName($continent['name'] ?? null)
->withContinentCode($continent['code'] ?? null)
->withPhoneCode($country['phone_code'] ?? null)
->withCapital($country['capital'] ?? null)
->withTld($country['tld'] ?? null)
->withFlagEmoji($flag['emoji'] ?? null)
->withFlagImg($flag['img'] ?? null)
->withCurrencyName($currency['name'] ?? null)
->withCurrencyCode($currency['code'] ?? null)
->withCurrencySymbol($currency['symbol'] ?? null)
->withGeonameId(isset($city['geoname_id']) ? (int) $city['geoname_id'] : null)
->withContinentGeonameId(isset($continent['geoname_id']) ? (int) $continent['geoname_id'] : null)
->withCountryGeonameId(isset($country['geoname_id']) ? (int) $country['geoname_id'] : null)
->withMetroCode(isset($city['metro_code']) ? (int) $city['metro_code'] : null)
->withFlagEmojiUnicode($flag['emoji_unicode'] ?? null)
->withAccuracyRadius(isset($city['accuracy_radius']) ? (int) $city['accuracy_radius'] : null)
->withTimeNow($timezone['time_now'] ?? null)
->withAsnNumber(isset($asn['number']) ? (int) $asn['number'] : null)
->withAsnName($asn['name'] ?? null)
->withRegisteredCountryName($registeredCountry['name'] ?? null)
->withRegisteredCountryCode($registeredCountry['code'] ?? null)
->withRegisteredCountryGeonameId(isset($registeredCountry['geoname_id']) ? (int) $registeredCountry['geoname_id'] : null);
return new AddressCollection([$address]);
}
}