|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Teca\IpValidator; |
|
4
|
|
|
|
|
5
|
|
|
use Anax\Commons\ContainerInjectableInterface; |
|
6
|
|
|
use Anax\Commons\ContainerInjectableTrait; |
|
7
|
|
|
|
|
8
|
|
|
class IpValidator implements ContainerInjectableInterface |
|
9
|
|
|
{ |
|
10
|
|
|
use ContainerInjectableTrait; |
|
11
|
|
|
|
|
12
|
|
|
private $url = 'http://api.ipstack.com/'; |
|
13
|
|
|
private $apiKey = ''; |
|
14
|
|
|
|
|
15
|
19 |
|
public function setUrl(string $url) : void |
|
16
|
|
|
{ |
|
17
|
19 |
|
$this->url = $url; |
|
18
|
19 |
|
} |
|
19
|
|
|
|
|
20
|
19 |
|
public function setApiKey(string $apiKey) : void |
|
21
|
|
|
{ |
|
22
|
19 |
|
$this->apiKey = $apiKey; |
|
23
|
19 |
|
} |
|
24
|
|
|
|
|
25
|
10 |
|
public function verifyIpv4(string $ipAddress) : bool |
|
26
|
|
|
{ |
|
27
|
10 |
|
return filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
10 |
|
public function verifyIpv6(string $ipAddress) : bool |
|
31
|
|
|
{ |
|
32
|
10 |
|
return filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
7 |
|
public function getDomain(string $ipAddress) : string |
|
36
|
|
|
{ |
|
37
|
7 |
|
if (!$this->verifyIpv4($ipAddress) && !$this->verifyIpv6($ipAddress)) { |
|
38
|
2 |
|
return ""; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
6 |
|
$host = gethostbyaddr($ipAddress); |
|
42
|
6 |
|
return $host !== $ipAddress ? $host : ""; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
8 |
|
protected function noGeo() : array |
|
46
|
|
|
{ |
|
47
|
|
|
return [ |
|
48
|
8 |
|
"latitude" => null, |
|
49
|
|
|
"longitude" => null, |
|
50
|
|
|
"country_name" => null, |
|
51
|
|
|
"region_name" => null, |
|
52
|
|
|
"city" => null |
|
53
|
|
|
]; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
8 |
|
public function getGeo(string $ipAddress) : array |
|
57
|
|
|
{ |
|
58
|
8 |
|
if (!$this->verifyIpv4($ipAddress) && !$this->verifyIpv6($ipAddress)) { |
|
59
|
3 |
|
return $this->noGeo(); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
5 |
|
$url = $this->url . $ipAddress; |
|
63
|
|
|
|
|
64
|
5 |
|
if ($this->apiKey !== '') { |
|
65
|
|
|
$url .= '?access_key=' . $this->apiKey; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
5 |
|
$data = $this->curl($url); |
|
69
|
|
|
|
|
70
|
5 |
|
return $data; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
protected function curl(string $url) : array |
|
74
|
|
|
{ |
|
75
|
|
|
$curl = curl_init(); |
|
76
|
|
|
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); |
|
|
|
|
|
|
77
|
|
|
curl_setopt($curl, CURLOPT_URL, $url); |
|
78
|
|
|
|
|
79
|
|
|
$data = curl_exec($curl); |
|
|
|
|
|
|
80
|
|
|
curl_close($curl); |
|
|
|
|
|
|
81
|
|
|
|
|
82
|
|
|
return json_decode($data, true); |
|
83
|
|
|
} |
|
84
|
|
|
} |
|
85
|
|
|
|