Completed
Push — master ( f4fe7d...26730f )
by Tobias
07:42
created

GeoPlugin::executeQuery()   D

Complexity

Conditions 20
Paths 5

Size

Total Lines 48
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 29
CRAP Score 20.1073

Importance

Changes 0
Metric Value
dl 0
loc 48
ccs 29
cts 31
cp 0.9355
rs 4.8892
c 0
b 0
f 0
cc 20
eloc 31
nc 5
nop 1
crap 20.1073

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\GeoPlugin;
14
15
use Geocoder\Collection;
16
use Geocoder\Exception\InvalidServerResponse;
17
use Geocoder\Exception\UnsupportedOperation;
18
use Geocoder\Model\Address;
19
use Geocoder\Model\AddressCollection;
20
use Geocoder\Query\GeocodeQuery;
21
use Geocoder\Query\ReverseQuery;
22
use Geocoder\Http\Provider\AbstractHttpProvider;
23
use Geocoder\Provider\Provider;
24
25
/**
26
 * @author Andrea Cristaudo <[email protected]>
27
 */
28
final class GeoPlugin extends AbstractHttpProvider implements Provider
29
{
30
    /**
31
     * @var string
32
     */
33
    const GEOCODE_ENDPOINT_URL = 'http://www.geoplugin.net/json.gp?ip=%s';
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 16
    public function geocodeQuery(GeocodeQuery $query): Collection
39
    {
40 16
        $address = $query->getText();
41 16
        if (!filter_var($address, FILTER_VALIDATE_IP)) {
42 1
            throw new UnsupportedOperation('The GeoPlugin provider does not support street addresses, only IP addresses.');
43
        }
44
45 15
        if (in_array($address, ['127.0.0.1', '::1'])) {
46 2
            return new AddressCollection([$this->getLocationForLocalhost()]);
47
        }
48
49 13
        $url = sprintf(self::GEOCODE_ENDPOINT_URL, $address);
50
51 13
        return $this->executeQuery($url);
52
    }
53
54
    /**
55
     * {@inheritdoc}
56
     */
57 1
    public function reverseQuery(ReverseQuery $query): Collection
58
    {
59 1
        throw new UnsupportedOperation('The GeoPlugin provider is not able to do reverse geocoding.');
60
    }
61
62
    /**
63
     * {@inheritdoc}
64
     */
65 5
    public function getName(): string
66
    {
67 5
        return 'geo_plugin';
68
    }
69
70
    /**
71
     * @param string $url
72
     *
73
     * @return AddressCollection
74
     */
75 13
    private function executeQuery(string $url): AddressCollection
76
    {
77 13
        $content = $this->getUrlContents($url);
78 3
        $json = json_decode($content, true);
79
80 3
        if (!is_array($json) || !count($json)) {
81
            throw InvalidServerResponse::create($url);
82
        }
83
84 3
        if (!array_key_exists('geoplugin_status', $json) || (200 !== $json['geoplugin_status'] && 206 !== $json['geoplugin_status'])) {
85 1
            return new AddressCollection([]);
86
        }
87
88
        // Return empty collection if address was not found
89 2
        if ('' === $json['geoplugin_regionName']
90 2
        && '' === $json['geoplugin_regionCode']
91 2
        && '' === $json['geoplugin_city']
92 2
        && '' === $json['geoplugin_countryName']
93 2
        && '' === $json['geoplugin_countryCode']
94 2
        && '0' === $json['geoplugin_latitude']
95 2
        && '0' === $json['geoplugin_longitude']) {
96
            return new AddressCollection([]);
97
        }
98
99 2
        $data = array_filter($json);
100
101 2
        $adminLevels = [];
102
103 2
        $region = \igorw\get_in($data, ['geoplugin_regionName']);
104 2
        $regionCode = \igorw\get_in($data, ['geoplugin_regionCode']);
105
106 2
        if (null !== $region || null !== $regionCode) {
107 1
            $adminLevels[] = ['name' => $region, 'code' => $regionCode, 'level' => 1];
108
        }
109
110 2
        $results = [];
111 2
        $results[] = Address::createFromArray([
112 2
            'providedBy' => $this->getName(),
113 2
            'locality' => isset($data['geoplugin_city']) ? $data['geoplugin_city'] : null,
114 2
            'country' => isset($data['geoplugin_countryName']) ? $data['geoplugin_countryName'] : null,
115 2
            'countryCode' => isset($data['geoplugin_countryCode']) ? $data['geoplugin_countryCode'] : null,
116 2
            'adminLevels' => $adminLevels,
117 2
            'latitude' => isset($data['geoplugin_latitude']) ? $data['geoplugin_latitude'] : null,
118 2
            'longitude' => isset($data['geoplugin_longitude']) ? $data['geoplugin_longitude'] : null,
119
        ]);
120
121 2
        return new AddressCollection($results);
122
    }
123
}
124