GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.

GeoIP2::geocodeQuery()   D
last analyzed

Complexity

Conditions 19
Paths 10

Size

Total Lines 44
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 44
rs 4.9141
c 0
b 0
f 0
cc 19
eloc 28
nc 10
nop 1

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Collection;
16
use Geocoder\Model\Address;
17
use Geocoder\Model\AddressCollection;
18
use Geocoder\Query\GeocodeQuery;
19
use Geocoder\Query\ReverseQuery;
20
use Geocoder\Provider\AbstractProvider;
21
use Geocoder\Provider\Provider;
22
use Geocoder\Exception\UnsupportedOperation;
23
use Geocoder\Exception\InvalidCredentials;
24
use Geocoder\Exception\QuotaExceeded;
25
use GeoIp2\Exception\AddressNotFoundException;
26
use GeoIp2\Exception\AuthenticationException;
27
use GeoIp2\Exception\OutOfQueriesException;
28
29
/**
30
 * @author Jens Wiese <[email protected]>
31
 */
32
final class GeoIP2 extends AbstractProvider implements Provider
33
{
34
    /**
35
     * @var GeoIP2Adapter
36
     */
37
    private $adapter;
38
39
    public function __construct(GeoIP2Adapter $adapter)
40
    {
41
        $this->adapter = $adapter;
42
    }
43
44
    /**
45
     * {@inheritdoc}
46
     */
47
    public function geocodeQuery(GeocodeQuery $query): Collection
48
    {
49
        $address = $query->getText();
50
        $locale = $query->getLocale() ?: 'en'; // Default to English
51
        if (!filter_var($address, FILTER_VALIDATE_IP)) {
52
            throw new UnsupportedOperation('The GeoIP2 provider does not support street addresses, only IP addresses.');
53
        }
54
55
        if ('127.0.0.1' === $address) {
56
            return new AddressCollection([$this->getLocationForLocalhost()]);
57
        }
58
59
        $result = json_decode($this->executeQuery($address));
60
61
        if (null === $result) {
62
            return new AddressCollection([]);
63
        }
64
65
        $adminLevels = [];
66
        if (isset($result->subdivisions) && is_array($result->subdivisions)) {
67
            foreach ($result->subdivisions as $i => $subdivision) {
68
                $name = (isset($subdivision->names->{$locale}) ? $subdivision->names->{$locale} : null);
69
                $code = (isset($subdivision->iso_code) ? $subdivision->iso_code : null);
70
71
                if (null !== $name || null !== $code) {
72
                    $adminLevels[] = ['name' => $name, 'code' => $code, 'level' => $i + 1];
73
                }
74
            }
75
        }
76
77
        return new AddressCollection([
78
            Address::createFromArray([
79
                'providedBy' => $this->getName(),
80
                'countryCode' => (isset($result->country->iso_code) ? $result->country->iso_code : null),
81
                'country' => (isset($result->country->names->{$locale}) ? $result->country->names->{$locale} : null),
82
                'locality' => (isset($result->city->names->{$locale}) ? $result->city->names->{$locale} : null),
83
                'latitude' => (isset($result->location->latitude) ? $result->location->latitude : null),
84
                'longitude' => (isset($result->location->longitude) ? $result->location->longitude : null),
85
                'timezone' => (isset($result->location->time_zone) ? $result->location->time_zone : null),
86
                'postalCode' => (isset($result->postal->code) ? $result->postal->code : null),
87
                'adminLevels' => $adminLevels,
88
            ]),
89
        ]);
90
    }
91
92
    /**
93
     * {@inheritdoc}
94
     */
95
    public function reverseQuery(ReverseQuery $query): Collection
96
    {
97
        throw new UnsupportedOperation('The GeoIP2 provider is not able to do reverse geocoding.');
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103
    public function getName(): string
104
    {
105
        return 'geoip2';
106
    }
107
108
    /**
109
     * @param string $address
110
     */
111
    private function executeQuery(string $address): string
112
    {
113
        $uri = sprintf('file://geoip?%s', $address);
114
115
        try {
116
            $result = $this->adapter->getContent($uri);
117
        } catch (AddressNotFoundException $e) {
118
            return '';
119
        } catch (AuthenticationException $e) {
120
            throw new InvalidCredentials(
121
                $e->getMessage(),
122
                $e->getCode(),
123
                $e
124
            );
125
        } catch (OutOfQueriesException $e) {
126
            throw new QuotaExceeded(
127
                $e->getMessage(),
128
                $e->getCode(),
129
                $e
130
            );
131
        }
132
133
        return $result;
134
    }
135
}
136