|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace yiicod\geo\adapters\ipstack; |
|
4
|
|
|
|
|
5
|
|
|
use yiicod\geo\base\GeoAdapterInterface; |
|
6
|
|
|
use yiicod\geo\base\GeoDataInterface; |
|
7
|
|
|
use yiicod\geo\exceptions\EmptyLocationDataException; |
|
8
|
|
|
use yiicod\geo\GeoData; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Class IpstackAdapter |
|
12
|
|
|
* Geo getter based on the ipstack source (http://ipstack.com/) |
|
13
|
|
|
* |
|
14
|
|
|
* @package yiicod\geo\adapters\ipstack |
|
15
|
|
|
* |
|
16
|
|
|
* @author Dmitry Turchanin |
|
17
|
|
|
*/ |
|
18
|
|
|
class IpstackAdapter implements GeoAdapterInterface |
|
19
|
|
|
{ |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* ipstack API-key |
|
23
|
|
|
* |
|
24
|
|
|
* @var string |
|
25
|
|
|
*/ |
|
26
|
|
|
public $apiKey = ''; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Loads location data from source for $ip |
|
30
|
|
|
* |
|
31
|
|
|
* @param $ip |
|
32
|
|
|
* |
|
33
|
|
|
* @return bool|string |
|
34
|
|
|
*/ |
|
35
|
|
|
public function loadLocationData($ip) |
|
36
|
|
|
{ |
|
37
|
|
|
$data = file_get_contents(sprintf('http://api.ipstack.com/%s?access_key=%s', $ip, $this->apiKey)); |
|
38
|
|
|
|
|
39
|
|
|
return $data; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Gets location data from loaded data |
|
44
|
|
|
* |
|
45
|
|
|
* @param $ip |
|
46
|
|
|
* |
|
47
|
|
|
* @return GeoDataInterface |
|
48
|
|
|
* |
|
49
|
|
|
* @throws EmptyLocationDataException |
|
50
|
|
|
*/ |
|
51
|
|
|
public function getLocationData($ip): GeoDataInterface |
|
52
|
|
|
{ |
|
53
|
|
|
$json = $this->loadLocationData($ip); |
|
54
|
|
|
|
|
55
|
|
|
$decoded = json_decode($json, true); |
|
56
|
|
|
|
|
57
|
|
|
if (empty($decoded)) { |
|
58
|
|
|
throw new EmptyLocationDataException("Location data is empty"); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
$data = [ |
|
62
|
|
|
'ip' => $ip, |
|
63
|
|
|
'countryCode' => $decoded['country_code'] ?? null, |
|
64
|
|
|
'countryName' => $decoded['country_name'] ?? null, |
|
65
|
|
|
'regionName' => $decoded['region_name'] ?? null, |
|
66
|
|
|
'regionCode' => $decoded['region_code'] ?? null, |
|
67
|
|
|
'city' => $decoded['city'] ?? null, |
|
68
|
|
|
'latitude' => $decoded['latitude'] ?? null, |
|
69
|
|
|
'longitude' => $decoded['longitude'] ?? null, |
|
70
|
|
|
]; |
|
71
|
|
|
|
|
72
|
|
|
$result = new GeoData($data); |
|
73
|
|
|
|
|
74
|
|
|
return $result; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
|
|
/** |
|
78
|
|
|
* Gets adapter's name |
|
79
|
|
|
* |
|
80
|
|
|
* @return string |
|
81
|
|
|
*/ |
|
82
|
|
|
public function getName(): string |
|
83
|
|
|
{ |
|
84
|
|
|
return 'ipstack_'; |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|