Completed
Push — mawiki ( ed8c52 )
by Jeroen De
08:10
created

NominatimGeocoder::getRequestUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
1
<?php
2
3
namespace Maps\Geocoders;
4
5
use DataValues\Geo\Values\LatLongValue;
6
use FileFetcher\FileFetcher;
7
8
/**
9
 * Webservice documentation: http://wiki.openstreetmap.org/wiki/Nominatim
10
 *
11
 * @since 3.8
12
 *
13
 * @licence GNU GPL v2+
14
 * @author Peter Grassberger < [email protected] >
15
 * @author Jeroen De Dauw < [email protected] >
16
 */
17
class NominatimGeocoder implements Geocoder {
18
19
	private $fileFetcher;
20
21
	public function __construct( FileFetcher $fileFetcher ) {
22
		$this->fileFetcher = $fileFetcher;
23
	}
24
25
	/**
26
	 * @param string $address
27
	 *
28
	 * @return LatLongValue|null
29
	 */
30
	public function geocode( $address ) {
31
		$response = $this->fileFetcher->fetchFile( $this->getRequestUrl( $address ) );
32
33
		$jsonResponse = json_decode( $response );
34
35
		if ( !is_array( $jsonResponse ) || count( $jsonResponse ) < 1 ) {
36
			return null;
37
		}
38
39
		$location  = $jsonResponse[0];
40
41
		if ( !$location->lat || !$location->lon ) return null;
42
43
		return new LatLongValue( $location->lat, $location->lon );
44
	}
45
46
	/**
47
	 * @param string $address
48
	 *
49
	 * @return string
50
	 */
51
	private function getRequestUrl( $address ) {
52
		return 'https://nominatim.openstreetmap.org/search?format=jsonv2&limit=1&q=' . urlencode( $address );
53
	}
54
55
}
56