-
Notifications
You must be signed in to change notification settings - Fork 521
Expand file tree
/
Copy pathIpApi.php
More file actions
155 lines (126 loc) · 4.56 KB
/
IpApi.php
File metadata and controls
155 lines (126 loc) · 4.56 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
<?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\IpApi;
use Geocoder\Collection;
use Geocoder\Exception\InvalidArgument;
use Geocoder\Exception\InvalidCredentials;
use Geocoder\Exception\InvalidServerResponse;
use Geocoder\Exception\UnsupportedOperation;
use Geocoder\Http\Provider\AbstractHttpProvider;
use Geocoder\Model\AddressBuilder;
use Geocoder\Model\AddressCollection;
use Geocoder\Provider\IpApi\Model\IpApiLocation;
use Geocoder\Query\GeocodeQuery;
use Geocoder\Query\ReverseQuery;
use Psr\Http\Client\ClientInterface;
final class IpApi extends AbstractHttpProvider
{
private const URL = '{host_prefix}ip-api.com/json/{ip}';
private const FIELDS = 'status,message,lat,lon,city,district,zip,country,countryCode,timezone,regionName,region,currency,callingCode,proxy,hosting';
private string|null $apiKey;
public function __construct(ClientInterface $client, string $apiKey = null)
{
$this->apiKey = $apiKey;
parent::__construct($client);
}
#[\Override]
public function geocodeQuery(GeocodeQuery $query): Collection
{
$ip = $query->getText();
if (!filter_var($ip, FILTER_VALIDATE_IP)) {
throw new UnsupportedOperation('The ip-api provider does not support street addresses.');
}
if (in_array($ip, ['127.0.0.1', '::1'])) {
return new AddressCollection([$this->getLocationForLocalhost()]);
}
$url = $this->buildUrl($ip, $query->getLocale());
$body = $this->getUrlContents($url);
$data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);
if ('fail' === $data['status']) {
$this->throwError($data['message']);
}
$location = $this->buildLocation($data);
return new AddressCollection([$location]);
}
#[\Override]
public function reverseQuery(ReverseQuery $query): Collection
{
throw new UnsupportedOperation('The ip-api provider is not able to do reverse geocoding.');
}
#[\Override]
public function getName(): string
{
return 'ip-api';
}
private function buildUrl(string $ip, string|null $locale): string
{
$baseUrl = strtr(self::URL, [
'{host_prefix}' => $this->apiKey ? 'https://pro.' : 'http://',
'{ip}' => $ip,
]);
$query = http_build_query(array_filter([
'key' => $this->apiKey,
'lang' => $locale,
'fields' => self::FIELDS,
]));
return $baseUrl.'?'.$query;
}
/**
* @param array<string, scalar> $data
*/
private function buildLocation(array $data): IpApiLocation
{
$data = array_map(
static fn ($value) => '' === $value ? null : $value,
$data,
);
$builder = new AddressBuilder($this->getName());
$builder->setCoordinates($data['lat'], $data['lon']);
$builder->setLocality($data['city']);
$builder->setSubLocality($data['district']);
$builder->setPostalCode($data['zip']);
$builder->setCountry($data['country']);
$builder->setCountryCode($data['countryCode']);
$builder->setTimezone($data['timezone']);
if ($data['regionName']) {
$builder->addAdminLevel(1, $data['regionName'], $data['region']);
}
/** @var IpApiLocation $location */
$location = $builder->build(IpApiLocation::class);
return $location
->withCurrency($data['currency'] ?? null)
->withCallingCode($data['callingCode'] ?? null)
->withIsProxy($data['proxy'])
->withIsHosting($data['hosting']);
}
/**
* @see https://members.ip-api.com/faq#errors
*
* @return never
*/
private function throwError(string $message)
{
if (
in_array($message, ['private range', 'reserved range', 'invalid query'], true)
|| str_contains($message, 'Origin restriction')
|| str_contains($message, 'IP range restriction')
|| str_contains($message, 'Calling IP restriction')
) {
throw new InvalidArgument($message);
}
if (
str_contains($message, 'invalid/expired key')
|| str_contains($message, 'no API key supplied')
) {
throw new InvalidCredentials($message);
}
throw new InvalidServerResponse($message);
}
}