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.
Completed
Push — master ( 27954e...8824ec )
by Tobias
04:24 queued 02:19
created

LocationIQ::reverseQuery()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 13
nc 2
nop 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\LocationIQ;
14
15
use Geocoder\Collection;
16
use Geocoder\Exception\InvalidServerResponse;
17
use Geocoder\Exception\InvalidCredentials;
18
use Geocoder\Location;
19
use Geocoder\Model\AddressBuilder;
20
use Geocoder\Model\AddressCollection;
21
use Geocoder\Query\GeocodeQuery;
22
use Geocoder\Query\ReverseQuery;
23
use Geocoder\Http\Provider\AbstractHttpProvider;
24
use Geocoder\Provider\Provider;
25
use Http\Client\HttpClient;
26
27
/**
28
 * @author Srihari Thalla <[email protected]>
29
 */
30
final class LocationIQ extends AbstractHttpProvider implements Provider
31
{
32
    /**
33
     * @var string
34
     */
35
    const BASE_API_URL = 'https://locationiq.org/v1';
36
37
    /**
38
     * @var string
39
     */
40
    private $apiKey;
41
42
    /**
43
     * @param HttpClient $client an HTTP adapter
44
     * @param string     $apiKey an API key
45
     */
46
    public function __construct(HttpClient $client, string $apiKey)
47
    {
48
        if (empty($apiKey)) {
49
            throw new InvalidCredentials('No API key provided.');
50
        }
51
52
        $this->apiKey = $apiKey;
53
54
        parent::__construct($client);
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function geocodeQuery(GeocodeQuery $query): Collection
61
    {
62
        $address = $query->getText();
63
64
        $url = sprintf($this->getGeocodeEndpointUrl(), urlencode($address), $query->getLimit());
65
66
        $content = $this->executeQuery($url, $query->getLocale());
67
68
        $doc = new \DOMDocument();
69
        if (!@$doc->loadXML($content) || null === $doc->getElementsByTagName('searchresults')->item(0)) {
70
            throw InvalidServerResponse::create($url);
71
        }
72
73
        $searchResult = $doc->getElementsByTagName('searchresults')->item(0);
74
        $places = $searchResult->getElementsByTagName('place');
75
76
        if (null === $places || 0 === $places->length) {
77
            return new AddressCollection([]);
78
        }
79
80
        $results = [];
81
        foreach ($places as $place) {
82
            $results[] = $this->xmlResultToArray($place, $place);
83
        }
84
85
        return new AddressCollection($results);
86
    }
87
88
    /**
89
     * {@inheritdoc}
90
     */
91
    public function reverseQuery(ReverseQuery $query): Collection
92
    {
93
        $coordinates = $query->getCoordinates();
94
        $longitude = $coordinates->getLongitude();
95
        $latitude = $coordinates->getLatitude();
96
        $url = sprintf($this->getReverseEndpointUrl(), $latitude, $longitude, $query->getData('zoom', 18));
97
        $content = $this->executeQuery($url, $query->getLocale());
98
99
        $doc = new \DOMDocument();
100
        if (!@$doc->loadXML($content) || $doc->getElementsByTagName('error')->length > 0) {
101
            return new AddressCollection([]);
102
        }
103
104
        $searchResult = $doc->getElementsByTagName('reversegeocode')->item(0);
105
        $addressParts = $searchResult->getElementsByTagName('addressparts')->item(0);
106
        $result = $searchResult->getElementsByTagName('result')->item(0);
107
108
        return new AddressCollection([$this->xmlResultToArray($result, $addressParts)]);
109
    }
110
111
    /**
112
     * @param \DOMElement $resultNode
113
     * @param \DOMElement $addressNode
114
     *
115
     * @return Location
116
     */
117
    private function xmlResultToArray(\DOMElement $resultNode, \DOMElement $addressNode): Location
118
    {
119
        $builder = new AddressBuilder($this->getName());
120
121
        foreach (['state', 'county'] as $i => $tagName) {
122
            if (null !== ($adminLevel = $this->getNodeValue($addressNode->getElementsByTagName($tagName)))) {
123
                $builder->addAdminLevel($i + 1, $adminLevel, '');
124
            }
125
        }
126
127
        // get the first postal-code when there are many
128
        $postalCode = $this->getNodeValue($addressNode->getElementsByTagName('postcode'));
129
        if (!empty($postalCode)) {
130
            $postalCode = current(explode(';', $postalCode));
131
        }
132
        $builder->setPostalCode($postalCode);
133
        $builder->setStreetName($this->getNodeValue($addressNode->getElementsByTagName('road')) ?: $this->getNodeValue($addressNode->getElementsByTagName('pedestrian')));
134
        $builder->setStreetNumber($this->getNodeValue($addressNode->getElementsByTagName('house_number')));
135
        $builder->setLocality($this->getNodeValue($addressNode->getElementsByTagName('city')));
136
        $builder->setSubLocality($this->getNodeValue($addressNode->getElementsByTagName('suburb')));
137
        $builder->setCountry($this->getNodeValue($addressNode->getElementsByTagName('country')));
138
        $builder->setCountryCode(strtoupper($this->getNodeValue($addressNode->getElementsByTagName('country_code'))));
139
        $builder->setCoordinates($resultNode->getAttribute('lat'), $resultNode->getAttribute('lon'));
140
141
        $boundsAttr = $resultNode->getAttribute('boundingbox');
142
        if ($boundsAttr) {
143
            $bounds = [];
144
            list($bounds['south'], $bounds['north'], $bounds['west'], $bounds['east']) = explode(',', $boundsAttr);
145
            $builder->setBounds($bounds['south'], $bounds['north'], $bounds['west'], $bounds['east']);
146
        }
147
148
        return $builder->build();
149
    }
150
151
    /**
152
     * {@inheritdoc}
153
     */
154
    public function getName(): string
155
    {
156
        return 'locationiq';
157
    }
158
159
    /**
160
     * @param string      $url
161
     * @param string|null $locale
162
     *
163
     * @return string
164
     */
165
    private function executeQuery(string $url, string $locale = null): string
166
    {
167
        if (null !== $locale) {
168
            $url = sprintf('%s&accept-language=%s', $url, $locale);
169
        }
170
171
        return $this->getUrlContents($url);
172
    }
173
174
    private function getGeocodeEndpointUrl(): string
175
    {
176
        return self::BASE_API_URL.'/search.php?q=%s&format=xml&addressdetails=1&limit=%d&key='.$this->apiKey;
177
    }
178
179
    private function getReverseEndpointUrl(): string
180
    {
181
        return self::BASE_API_URL.'/reverse.php?format=xml&lat=%F&lon=%F&addressdetails=1&zoom=%d&key='.$this->apiKey;
182
    }
183
184
    private function getNodeValue(\DOMNodeList $element)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
185
    {
186
        return $element->length ? $element->item(0)->nodeValue : null;
187
    }
188
}
189