forked from geocoder-php/Geocoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeoIPs.php
More file actions
202 lines (166 loc) · 6.81 KB
/
Copy pathGeoIPs.php
File metadata and controls
202 lines (166 loc) · 6.81 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
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
<?php
/**
* 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;
use Geocoder\Exception\InvalidArgument;
use Geocoder\Exception\InvalidCredentials;
use Geocoder\Exception\NoResult;
use Geocoder\Exception\QuotaExceeded;
use Geocoder\Exception\UnsupportedOperation;
use Ivory\HttpAdapter\HttpAdapterInterface;
/**
* @author Andrea Cristaudo <andrea.cristaudo@gmail.com>
* @author Arthur Bodera <abodera@thinkscape.pro>
*
* @link http://www.geoips.com/en/developer/api-guide
*/
class GeoIPs extends AbstractHttpProvider implements Provider
{
/**
* @var string
*/
const GEOCODE_ENDPOINT_URL = 'http://api.geoips.com/ip/%s/key/%s/output/json/timezone/true/';
const CODE_SUCCESS = '200_1'; // The following results has been returned.
const CODE_NOT_FOUND = '200_2'; // No result set has been returned.
const CODE_BAD_KEY = '400_1'; // Error in the URI - The API call should include a API key parameter.
const CODE_BAD_IP = '400_2'; // Error in the URI - The API call should include a valid IP address.
const CODE_NOT_AUTHORIZED = '403_1'; // The API key associated with your request was not recognized.
const CODE_ACCOUNT_INACTIVE = '403_2'; // The API key has not been approved or has been disabled.
const CODE_LIMIT_EXCEEDED = '403_3'; // The service you have requested is over capacity.
/**
* @var string
*/
private $apiKey;
/**
* @param HttpAdapterInterface $adapter An HTTP adapter
* @param string $apiKey An API key
*/
public function __construct(HttpAdapterInterface $adapter, $apiKey)
{
parent::__construct($adapter);
$this->apiKey = $apiKey;
}
/**
* {@inheritDoc}
*/
public function geocode($address)
{
if (null === $this->apiKey) {
throw new InvalidCredentials('No API key provided.');
}
if (!filter_var($address, FILTER_VALIDATE_IP)) {
throw new UnsupportedOperation('The GeoIPs provider does not support street addresses, only IPv4 addresses.');
}
if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
throw new UnsupportedOperation('The GeoIPs provider does not support IPv6 addresses, only IPv4 addresses.');
}
if ('127.0.0.1' === $address) {
return $this->returnResults([ $this->getLocalhostDefaults() ]);
}
$query = sprintf(self::GEOCODE_ENDPOINT_URL, $address, $this->apiKey);
return $this->executeQuery($query);
}
/**
* {@inheritDoc}
*/
public function reverse($latitude, $longitude)
{
throw new UnsupportedOperation('The GeoIPs provider is not able to do reverse geocoding.');
}
/**
* {@inheritDoc}
*/
public function getName()
{
return 'geo_ips';
}
/**
* @param string $query
*/
private function executeQuery($query)
{
$content = (string) $this->getAdapter()->get($query)->getBody();
if (empty($content)) {
throw new NoResult(sprintf('Invalid response from GeoIPs API for query "%s".', $query));
}
$json = json_decode($content, true);
if (isset($json['error'])) {
switch ($json['error']['code']) {
case static::CODE_BAD_IP:
throw new InvalidArgument('The API call should include a valid IP address.');
case static::CODE_BAD_KEY:
throw new InvalidCredentials('The API call should include a API key parameter.');
case static::CODE_NOT_AUTHORIZED:
throw new InvalidCredentials('The API key associated with your request was not recognized.');
case static::CODE_ACCOUNT_INACTIVE:
throw new InvalidCredentials('The API key has not been approved or has been disabled.');
case static::CODE_LIMIT_EXCEEDED:
throw new QuotaExceeded('The service you have requested is over capacity.');
default:
throw new NoResult(sprintf(
'GeoIPs error %s%s%s%s - query: %s',
$json['error']['code'],
isset($json['error']['status']) ? ', ' . $json['error']['status'] : '',
isset($json['error']['message']) ? ', ' . $json['error']['message'] : '',
isset($json['error']['notes']) ? ', ' . $json['error']['notes'] : '',
$query
));
}
}
if (!is_array($json) || empty($json) || empty($json['response']) || empty($json['response']['code'])) {
throw new NoResult(sprintf('Invalid response from GeoIPs API for query "%s".', $query));
}
$response = $json['response'];
// Check response code
switch ($response['code']) {
case static::CODE_NOT_FOUND:
throw new NoResult();
case static::CODE_SUCCESS;
// everything is ok
break;
default:
throw new NoResult(sprintf(
'The GeoIPs API returned unknown result code "%s" for query: "%s".',
$response['code'],
$query
));
}
// Make sure that we do have proper result array
if (empty($response['location']) || !is_array($response['location'])) {
throw new NoResult(sprintf('Invalid response from GeoIPs API for query "%s".', $query));
}
$location = array_map(function ($value) {
return '' === $value ? null : $value;
}, $response['location']);
$adminLevels = [];
if (null !== $location['region_name'] || null !== $location['region_code']) {
$adminLevels[] = [
'name' => $location['region_name'],
'code' => $location['region_code'],
'level' => 1
];
}
if (null !== $location['county_name']) {
$adminLevels[] = [
'name' => $location['county_name'],
'level' => 2
];
}
$results = [];
$results[] = array_merge($this->getDefaults(), array(
'country' => $location['country_name'],
'countryCode' => $location['country_code'],
'adminLevels' => $adminLevels,
'locality' => $location['city_name'],
'latitude' => $location['latitude'],
'longitude' => $location['longitude'],
'timezone' => $location['timezone'],
));
return $this->returnResults($results);
}
}