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 ( 691675...503bab )
by Tobias
07:29 queued 04:40
created

Nominatim::executeQuery()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 2
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\Nominatim;
14
15
use Geocoder\Collection;
16
use Geocoder\Exception\InvalidServerResponse;
17
use Geocoder\Exception\UnsupportedOperation;
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 Niklas Närhinen <[email protected]>
29
 */
30
final class Nominatim extends AbstractHttpProvider implements Provider
31
{
32
    /**
33
     * @var string
34
     */
35
    private $rootUrl;
36
37
    /**
38
     * @param HttpClient  $client
39
     * @param string|null $locale
0 ignored issues
show
Bug introduced by
There is no parameter named $locale. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
40
     *
41
     * @return Nominatim
42
     */
43
    public static function withOpenStreetMapServer(HttpClient $client)
44
    {
45
        return new self($client, 'https://nominatim.openstreetmap.org');
46
    }
47
48
    /**
49
     * @param HttpClient $client  an HTTP adapter
50
     * @param string     $rootUrl Root URL of the nominatim server
51
     */
52
    public function __construct(HttpClient $client, $rootUrl)
53
    {
54
        parent::__construct($client);
55
56
        $this->rootUrl = rtrim($rootUrl, '/');
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function geocodeQuery(GeocodeQuery $query): Collection
63
    {
64
        $address = $query->getText();
65
        // This API does not support IPv6
66
        if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
67
            throw new UnsupportedOperation('The Nominatim provider does not support IPv6 addresses.');
68
        }
69
70
        if ('127.0.0.1' === $address) {
71
            return new AddressCollection([$this->getLocationForLocalhost()]);
72
        }
73
74
        $url = sprintf($this->getGeocodeEndpointUrl(), urlencode($address), $query->getLimit());
75
        $content = $this->executeQuery($url, $query->getLocale());
76
77
        $doc = new \DOMDocument();
78
        if (!@$doc->loadXML($content) || null === $doc->getElementsByTagName('searchresults')->item(0)) {
79
            throw InvalidServerResponse::create($url);
80
        }
81
82
        $searchResult = $doc->getElementsByTagName('searchresults')->item(0);
83
        $places = $searchResult->getElementsByTagName('place');
84
85
        if (null === $places || 0 === $places->length) {
86
            return new AddressCollection([]);
87
        }
88
89
        $results = [];
90
        foreach ($places as $place) {
91
            $results[] = $this->xmlResultToArray($place, $place);
92
        }
93
94
        return new AddressCollection($results);
95
    }
96
97
    /**
98
     * {@inheritdoc}
99
     */
100
    public function reverseQuery(ReverseQuery $query): Collection
101
    {
102
        $coordinates = $query->getCoordinates();
103
        $longitude = $coordinates->getLongitude();
104
        $latitude = $coordinates->getLatitude();
105
        $url = sprintf($this->getReverseEndpointUrl(), $latitude, $longitude, $query->getData('zoom', 18));
106
        $content = $this->executeQuery($url, $query->getLocale());
107
108
        $doc = new \DOMDocument();
109
        if (!@$doc->loadXML($content) || $doc->getElementsByTagName('error')->length > 0) {
110
            return new AddressCollection([]);
111
        }
112
113
        $searchResult = $doc->getElementsByTagName('reversegeocode')->item(0);
114
        $addressParts = $searchResult->getElementsByTagName('addressparts')->item(0);
115
        $result = $searchResult->getElementsByTagName('result')->item(0);
116
117
        return new AddressCollection([$this->xmlResultToArray($result, $addressParts)]);
118
    }
119
120
    /**
121
     * @param \DOMElement $resultNode
122
     * @param \DOMElement $addressNode
123
     *
124
     * @return Location
125
     */
126
    private function xmlResultToArray(\DOMElement $resultNode, \DOMElement $addressNode): Location
127
    {
128
        $builder = new AddressBuilder($this->getName());
129
130
        foreach (['state', 'county'] as $i => $tagName) {
131
            if (null !== ($adminLevel = $this->getNodeValue($addressNode->getElementsByTagName($tagName)))) {
132
                $builder->addAdminLevel($i + 1, $adminLevel, '');
133
            }
134
        }
135
136
        // get the first postal-code when there are many
137
        $postalCode = $this->getNodeValue($addressNode->getElementsByTagName('postcode'));
138
        if (!empty($postalCode)) {
139
            $postalCode = current(explode(';', $postalCode));
140
        }
141
        $builder->setPostalCode($postalCode);
142
        $builder->setStreetName($this->getNodeValue($addressNode->getElementsByTagName('road')) ?: $this->getNodeValue($addressNode->getElementsByTagName('pedestrian')));
143
        $builder->setStreetNumber($this->getNodeValue($addressNode->getElementsByTagName('house_number')));
144
        $builder->setLocality($this->getNodeValue($addressNode->getElementsByTagName('city')));
145
        $builder->setSubLocality($this->getNodeValue($addressNode->getElementsByTagName('suburb')));
146
        $builder->setCountry($this->getNodeValue($addressNode->getElementsByTagName('country')));
147
148
        $countryCode = $this->getNodeValue($addressNode->getElementsByTagName('country_code'));
149
        if (!empty($countryCode)) {
150
            $countryCode = strtoupper($countryCode);
151
        }
152
        $builder->setCountryCode($countryCode);
153
        $builder->setCoordinates($resultNode->getAttribute('lat'), $resultNode->getAttribute('lon'));
154
155
        $boundsAttr = $resultNode->getAttribute('boundingbox');
156
        if ($boundsAttr) {
157
            $bounds = [];
158
            list($bounds['south'], $bounds['north'], $bounds['west'], $bounds['east']) = explode(',', $boundsAttr);
159
            $builder->setBounds($bounds['south'], $bounds['north'], $bounds['west'], $bounds['east']);
160
        }
161
162
        return $builder->build();
163
    }
164
165
    /**
166
     * {@inheritdoc}
167
     */
168
    public function getName(): string
169
    {
170
        return 'nominatim';
171
    }
172
173
    /**
174
     * @param string      $url
175
     * @param string|null $locale
176
     *
177
     * @return string
178
     */
179
    private function executeQuery(string $url, string $locale = null): string
180
    {
181
        if (null !== $locale) {
182
            $url = sprintf('%s&accept-language=%s', $url, $locale);
183
        }
184
185
        return $this->getUrlContents($url);
186
    }
187
188
    private function getGeocodeEndpointUrl(): string
189
    {
190
        return $this->rootUrl.'/search?q=%s&format=xml&addressdetails=1&limit=%d';
191
    }
192
193
    private function getReverseEndpointUrl(): string
194
    {
195
        return $this->rootUrl.'/reverse?format=xml&lat=%F&lon=%F&addressdetails=1&zoom=%d';
196
    }
197
198
    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...
199
    {
200
        return $element->length ? $element->item(0)->nodeValue : null;
201
    }
202
}
203