Code

< 40 %
40-60 %
> 60 %
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Geocoder package.
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license    MIT License
11
 */
12
13
namespace Geocoder\Provider\GeoIP2;
14
15
use Geocoder\Exception\InvalidArgument;
16
use Geocoder\Exception\UnsupportedOperation;
17
use GeoIp2\ProviderInterface;
18
19
/**
20
 * @author Jens Wiese <[email protected]>
21
 */
22
class GeoIP2Adapter
23
{
24
    /**
25
     * GeoIP2 models (e.g. city or country).
26
     */
27
    public const GEOIP2_MODEL_CITY = 'city';
28
29
    public const GEOIP2_MODEL_COUNTRY = 'country';
30
31
    /**
32
     * @var ProviderInterface
33
     */
34
    protected $geoIp2Provider;
35
36
    /**
37
     * @var string
38
     */
39
    protected $geoIP2Model;
40
41
    /**
42
     * @param string $geoIP2Model (e.g. self::GEOIP2_MODEL_CITY)
43
     */
44 9
    public function __construct(ProviderInterface $geoIpProvider, $geoIP2Model = self::GEOIP2_MODEL_CITY)
45
    {
46 9
        $this->geoIp2Provider = $geoIpProvider;
47
48 9
        if (false === $this->isSupportedGeoIP2Model($geoIP2Model)) {
49 1
            throw new UnsupportedOperation(sprintf('Model "%s" is not available.', $geoIP2Model));
50
        }
51
52 9
        $this->geoIP2Model = $geoIP2Model;
53
    }
54
55
    /**
56
     * Returns the content fetched from a given resource.
57
     *
58
     * @param string $url (e.g. file://database?127.0.0.1)
59
     */
60 7
    public function getContent(string $url): string
61
    {
62 7
        if (false === filter_var($url, FILTER_VALIDATE_URL)) {
63 1
            throw new InvalidArgument(sprintf('"%s" must be called with a valid url. Got "%s" instead.', __METHOD__, $url));
64
        }
65
66 6
        $ipAddress = parse_url($url, PHP_URL_QUERY);
67
68 6
        if (false === filter_var($ipAddress, FILTER_VALIDATE_IP)) {
69 1
            throw new InvalidArgument('URL must contain a valid query-string (an IP address, 127.0.0.1 for instance)');
70
        }
71
72 5
        $result = $this->geoIp2Provider
73 5
            ->{$this->geoIP2Model}($ipAddress)
74 5
            ->jsonSerialize();
75
76 5
        return json_encode($result);
77
    }
78
79
    /**
80
     * Returns the name of the Adapter.
81
     */
82 1
    public function getName(): string
83
    {
84 1
        return 'maxmind_geoip2';
85
    }
86
87
    /**
88
     * Returns whether method is supported by GeoIP2.
89
     */
90 9
    protected function isSupportedGeoIP2Model(string $method): bool
91
    {
92 9
        $availableMethods = [
93 9
            self::GEOIP2_MODEL_CITY,
94 9
            self::GEOIP2_MODEL_COUNTRY,
95 9
        ];
96
97 9
        return in_array($method, $availableMethods);
98
    }
99
}
100