forked from geocoder-php/Geocoder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeoIP2Adapter.php
More file actions
110 lines (92 loc) · 2.68 KB
/
Copy pathGeoIP2Adapter.php
File metadata and controls
110 lines (92 loc) · 2.68 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
<?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\Adapter;
use GeoIp2\ProviderInterface;
use Geocoder\Exception\InvalidArgument;
use Geocoder\Exception\UnsupportedOperation;
use Geocoder\Provider\LocaleTrait;
/**
* @author Jens Wiese <jens@howtrueisfalse.de>
*/
class GeoIP2Adapter
{
/**
* GeoIP2 models (e.g. city or country)
*/
const GEOIP2_MODEL_CITY = 'city';
const GEOIP2_MODEL_COUNTRY = 'country';
use LocaleTrait;
/**
* @var ProviderInterface
*/
protected $geoIp2Provider;
/**
* @var string
*/
protected $geoIP2Model;
/**
* @param \GeoIp2\ProviderInterface $geoIpProvider
* @param string $geoIP2Model (e.g. self::GEOIP2_MODEL_CITY)
*/
public function __construct(ProviderInterface $geoIpProvider, $geoIP2Model = self::GEOIP2_MODEL_CITY)
{
$this->geoIp2Provider = $geoIpProvider;
if (false === $this->isSupportedGeoIP2Model($geoIP2Model)) {
throw new UnsupportedOperation(
sprintf('Model "%s" is not available.', $geoIP2Model)
);
}
$this->geoIP2Model = $geoIP2Model;
}
/**
* Returns the content fetched from a given resource.
*
* @param string $url (e.g. file://database?127.0.0.1)
* @return string
*/
public function getContent($url)
{
if (false === filter_var($url, FILTER_VALIDATE_URL)) {
throw new InvalidArgument(
sprintf('"%s" must be called with a valid url. Got "%s" instead.', __METHOD__, $url)
);
}
$ipAddress = parse_url($url, PHP_URL_QUERY);
if (false === filter_var($ipAddress, FILTER_VALIDATE_IP)) {
throw new InvalidArgument('URL must contain a valid query-string (an IP address, 127.0.0.1 for instance)');
}
$result = $this->geoIp2Provider
->{$this->geoIP2Model}($ipAddress)
->jsonSerialize();
return json_encode($result);
}
/**
* Returns the name of the Adapter.
*
* @return string
*/
public function getName()
{
return 'maxmind_geoip2';
}
/**
* Returns whether method is supported by GeoIP2
*
* @param string $method
* @return bool
*/
protected function isSupportedGeoIP2Model($method)
{
$availableMethods = array(
self::GEOIP2_MODEL_CITY,
self::GEOIP2_MODEL_COUNTRY,
);
return in_array($method, $availableMethods);
}
}