-
Notifications
You must be signed in to change notification settings - Fork 0
/
GeoIP2Adapter.php
99 lines (80 loc) · 2.46 KB
/
GeoIP2Adapter.php
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
<?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\GeoIP2;
use Geocoder\Exception\InvalidArgument;
use Geocoder\Exception\UnsupportedOperation;
use GeoIp2\ProviderInterface;
/**
* @author Jens Wiese <jens@howtrueisfalse.de>
*/
class GeoIP2Adapter
{
/**
* GeoIP2 models (e.g. city or country).
*/
public const GEOIP2_MODEL_CITY = 'city';
public const GEOIP2_MODEL_COUNTRY = 'country';
/**
* @var ProviderInterface
*/
protected $geoIp2Provider;
/**
* @var string
*/
protected $geoIP2Model;
/**
* @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)
*/
public function getContent(string $url): string
{
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.
*/
public function getName(): string
{
return 'maxmind_geoip2';
}
/**
* Returns whether method is supported by GeoIP2.
*/
protected function isSupportedGeoIP2Model(string $method): bool
{
$availableMethods = [
self::GEOIP2_MODEL_CITY,
self::GEOIP2_MODEL_COUNTRY,
];
return in_array($method, $availableMethods);
}
}