Completed
Push — master ( 443de6...a55832 )
by Tobias
03:38
created

FreeGeoIp::reverseQuery()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
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\FreeGeoIp;
14
15
use Geocoder\Collection;
16
use Geocoder\Exception\InvalidArgument;
17
use Geocoder\Exception\UnsupportedOperation;
18
use Geocoder\Model\AddressBuilder;
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
use Http\Client\HttpClient;
25
26
/**
27
 * @author William Durand <[email protected]>
28
 */
29
final class FreeGeoIp extends AbstractHttpProvider implements Provider
30
{
31
    /**
32
     * @var string|null
33
     */
34
    private $baseUrl;
35
36
    /**
37
     * @param HttpClient $client
38
     * @param string     $baseUrl
39
     */
40 6
    public function __construct(HttpClient $client, string $baseUrl = null)
41
    {
42 6
        parent::__construct($client);
43
44 6
        $this->baseUrl = $baseUrl;
45 6
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 4
    public function geocodeQuery(GeocodeQuery $query): Collection
51
    {
52 4
        if (null === $this->baseUrl) {
53
            throw new InvalidArgument(sprintf(
54
                'The FreeGeoIp.net service no longer operates. See %s and %s for more information.',
55
                'http://freegeoip.net/shutdown',
56
                'https://github.com/geocoder-php/free-geoip-provider'
57
            ));
58
        }
59
60 4
        $address = $query->getText();
61 4
        if (!filter_var($address, FILTER_VALIDATE_IP)) {
62 1
            throw new UnsupportedOperation('The FreeGeoIp provider does not support street addresses.');
63
        }
64
65 3
        if (in_array($address, ['127.0.0.1', '::1'])) {
66 2
            return new AddressCollection([$this->getLocationForLocalhost()]);
67
        }
68
69 1
        $request = $this->getRequest(sprintf($this->baseUrl, $address));
70
71 1
        if (null !== $query->getLocale()) {
72
            $request = $request->withHeader('Accept-Language', $query->getLocale());
73
        }
74
75 1
        $body = $this->getParsedResponse($request);
76
        $data = json_decode($body, true);
77
78
        // Return empty collection if address was not found
79
        if ('' === $data['region_name']
80
        && '' === $data['region_code']
81
        && 0 === $data['latitude']
82
        && 0 === $data['longitude']
83
        && '' === $data['city']
84
        && '' === $data['zip_code']
85
        && '' === $data['country_name']
86
        && '' === $data['country_code']
87
        && '' === $data['time_zone']) {
88
            return new AddressCollection([]);
89
        }
90
91
        $builder = new AddressBuilder($this->getName());
92
93
        if (!empty($data['region_name'])) {
94
            $builder->addAdminLevel(1, $data['region_name'], $data['region_code'] ?? null);
95
        }
96
97
        if (0 !== $data['latitude'] || 0 !== $data['longitude']) {
98
            $builder->setCoordinates($data['latitude'] ?? null, $data['longitude'] ?? null);
99
        }
100
        $builder->setLocality(empty($data['city']) ? null : $data['city']);
101
        $builder->setPostalCode(empty($data['zip_code']) ? null : $data['zip_code']);
102
        $builder->setCountry(empty($data['country_name']) ? null : $data['country_name']);
103
        $builder->setCountryCode(empty($data['country_code']) ? null : $data['country_code']);
104
        $builder->setTimezone(empty($data['time_zone']) ? null : $data['time_zone']);
105
106
        return new AddressCollection([$builder->build()]);
107
    }
108
109
    /**
110
     * {@inheritdoc}
111
     */
112 1
    public function reverseQuery(ReverseQuery $query): Collection
113
    {
114 1
        throw new UnsupportedOperation('The FreeGeoIp provider is not able to do reverse geocoding.');
115
    }
116
117
    /**
118
     * {@inheritdoc}
119
     */
120 3
    public function getName(): string
121
    {
122 3
        return 'free_geo_ip';
123
    }
124
}
125