Completed
Push — master ( efe14a...8f3dc1 )
by Tobias
05:25
created

Nominatim.php (1 issue)

Labels
Severity

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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 Geocoder\Provider\Nominatim\Model\NominatimAddress;
26
use Http\Client\HttpClient;
27
28
/**
29
 * @author Niklas Närhinen <[email protected]>
30
 * @author Jonathan Beliën <[email protected]>
31
 */
32
final class Nominatim extends AbstractHttpProvider implements Provider
33
{
34
    /**
35
     * @var string
36
     */
37
    private $rootUrl;
38
39
    /**
40
     * @param HttpClient  $client
41
     * @param string|null $locale
0 ignored issues
show
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...
42
     *
43
     * @return Nominatim
44
     */
45 28
    public static function withOpenStreetMapServer(HttpClient $client)
46
    {
47 28
        return new self($client, 'https://nominatim.openstreetmap.org');
48
    }
49
50
    /**
51
     * @param HttpClient $client  an HTTP adapter
52
     * @param string     $rootUrl Root URL of the nominatim server
53
     */
54 28
    public function __construct(HttpClient $client, $rootUrl)
55
    {
56 28
        parent::__construct($client);
57
58 28
        $this->rootUrl = rtrim($rootUrl, '/');
59 28
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64 19
    public function geocodeQuery(GeocodeQuery $query): Collection
65
    {
66 19
        $address = $query->getText();
67
        // This API does not support IPv6
68 19
        if (filter_var($address, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
69 2
            throw new UnsupportedOperation('The Nominatim provider does not support IPv6 addresses.');
70
        }
71
72 17
        if ('127.0.0.1' === $address) {
73 1
            return new AddressCollection([$this->getLocationForLocalhost()]);
74
        }
75
76 16
        $url = sprintf($this->getGeocodeEndpointUrl(), urlencode($address), $query->getLimit());
77 16
        $content = $this->executeQuery($url, $query->getLocale());
78
79 6
        $doc = new \DOMDocument();
80 6
        if (!@$doc->loadXML($content) || null === $doc->getElementsByTagName('searchresults')->item(0)) {
81 2
            throw InvalidServerResponse::create($url);
82
        }
83
84 4
        $searchResult = $doc->getElementsByTagName('searchresults')->item(0);
85 4
        $attribution = $searchResult->getAttribute('attribution');
86 4
        $places = $searchResult->getElementsByTagName('place');
87
88 4
        if (null === $places || 0 === $places->length) {
89 1
            return new AddressCollection([]);
90
        }
91
92 3
        $results = [];
93 3
        foreach ($places as $place) {
94 3
            $results[] = $this->xmlResultToArray($place, $place, $attribution, false);
95
        }
96
97 3
        return new AddressCollection($results);
98
    }
99
100
    /**
101
     * {@inheritdoc}
102
     */
103 9
    public function reverseQuery(ReverseQuery $query): Collection
104
    {
105 9
        $coordinates = $query->getCoordinates();
106 9
        $longitude = $coordinates->getLongitude();
107 9
        $latitude = $coordinates->getLatitude();
108 9
        $url = sprintf($this->getReverseEndpointUrl(), $latitude, $longitude, $query->getData('zoom', 18));
109 9
        $content = $this->executeQuery($url, $query->getLocale());
110
111 4
        $doc = new \DOMDocument();
112 4
        if (!@$doc->loadXML($content) || $doc->getElementsByTagName('error')->length > 0) {
113 2
            return new AddressCollection([]);
114
        }
115
116 2
        $searchResult = $doc->getElementsByTagName('reversegeocode')->item(0);
117 2
        $attribution = $searchResult->getAttribute('attribution');
118 2
        $addressParts = $searchResult->getElementsByTagName('addressparts')->item(0);
119 2
        $result = $searchResult->getElementsByTagName('result')->item(0);
120
121 2
        return new AddressCollection([$this->xmlResultToArray($result, $addressParts, $attribution, true)]);
122
    }
123
124
    /**
125
     * @param \DOMElement $resultNode
126
     * @param \DOMElement $addressNode
127
     *
128
     * @return Location
129
     */
130 5
    private function xmlResultToArray(\DOMElement $resultNode, \DOMElement $addressNode, string $attribution, bool $reverse): Location
131
    {
132 5
        $builder = new AddressBuilder($this->getName());
133
134 5
        foreach (['state', 'county'] as $i => $tagName) {
135 5
            if (null !== ($adminLevel = $this->getNodeValue($addressNode->getElementsByTagName($tagName)))) {
136 5
                $builder->addAdminLevel($i + 1, $adminLevel, '');
137
            }
138
        }
139
140
        // get the first postal-code when there are many
141 5
        $postalCode = $this->getNodeValue($addressNode->getElementsByTagName('postcode'));
142 5
        if (!empty($postalCode)) {
143 4
            $postalCode = current(explode(';', $postalCode));
144
        }
145 5
        $builder->setPostalCode($postalCode);
146
147 5
        $localityFields = ['city', 'town', 'village', 'hamlet'];
148 5
        foreach ($localityFields as $localityField) {
149 5
            $localityFieldContent = $this->getNodeValue($addressNode->getElementsByTagName($localityField));
150 5
            if (!empty($localityFieldContent)) {
151 5
                $builder->setLocality($localityFieldContent);
152
153 5
                break;
154
            }
155
        }
156
157 5
        $builder->setStreetName($this->getNodeValue($addressNode->getElementsByTagName('road')) ?: $this->getNodeValue($addressNode->getElementsByTagName('pedestrian')));
158 5
        $builder->setStreetNumber($this->getNodeValue($addressNode->getElementsByTagName('house_number')));
159 5
        $builder->setSubLocality($this->getNodeValue($addressNode->getElementsByTagName('suburb')));
160 5
        $builder->setCountry($this->getNodeValue($addressNode->getElementsByTagName('country')));
161
162 5
        $countryCode = $this->getNodeValue($addressNode->getElementsByTagName('country_code'));
163 5
        if (!empty($countryCode)) {
164 5
            $countryCode = strtoupper($countryCode);
165
        }
166 5
        $builder->setCountryCode($countryCode);
167
168 5
        $builder->setCoordinates($resultNode->getAttribute('lat'), $resultNode->getAttribute('lon'));
169
170 5
        $boundsAttr = $resultNode->getAttribute('boundingbox');
171 5
        if ($boundsAttr) {
172 5
            $bounds = [];
173 5
            list($bounds['south'], $bounds['north'], $bounds['west'], $bounds['east']) = explode(',', $boundsAttr);
174 5
            $builder->setBounds($bounds['south'], $bounds['west'], $bounds['north'], $bounds['east']);
175
        }
176
177 5
        $location = $builder->build(NominatimAddress::class);
178 5
        $location = $location->withAttribution($attribution);
179 5
        $location = $location->withOSMId(intval($resultNode->getAttribute('osm_id')));
180 5
        $location = $location->withOSMType($resultNode->getAttribute('osm_type'));
181
182 5
        if (false === $reverse) {
183 3
            $location = $location->withClass($resultNode->getAttribute('class'));
184 3
            $location = $location->withDisplayName($resultNode->getAttribute('display_name'));
185 3
            $location = $location->withType($resultNode->getAttribute('type'));
186
        } else {
187 2
            $location = $location->withDisplayName($resultNode->nodeValue);
188
        }
189
190 5
        return $location;
191
    }
192
193
    /**
194
     * {@inheritdoc}
195
     */
196 6
    public function getName(): string
197
    {
198 6
        return 'nominatim';
199
    }
200
201
    /**
202
     * @param string      $url
203
     * @param string|null $locale
204
     *
205
     * @return string
206
     */
207 25
    private function executeQuery(string $url, string $locale = null): string
208
    {
209 25
        if (null !== $locale) {
210 4
            $url = sprintf('%s&accept-language=%s', $url, $locale);
211
        }
212
213 25
        return $this->getUrlContents($url);
214
    }
215
216 16
    private function getGeocodeEndpointUrl(): string
217
    {
218 16
        return $this->rootUrl.'/search?q=%s&format=xml&addressdetails=1&limit=%d';
219
    }
220
221 9
    private function getReverseEndpointUrl(): string
222
    {
223 9
        return $this->rootUrl.'/reverse?format=xml&lat=%F&lon=%F&addressdetails=1&zoom=%d';
224
    }
225
226 5
    private function getNodeValue(\DOMNodeList $element)
227
    {
228 5
        return $element->length ? $element->item(0)->nodeValue : null;
229
    }
230
}
231