Completed
Push — geonames-geocoder ( 01e909...af3b1c )
by Jeroen De
04:28
created

GoogleGeocoder::getRequestUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.0185

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 12
ccs 5
cts 6
cp 0.8333
rs 9.4285
cc 2
eloc 7
nc 2
nop 1
crap 2.0185
1
<?php
2
3
namespace Maps\Geocoders;
4
5
use DataValues\Geo\Values\LatLongValue;
6
use FileFetcher\FileFetcher;
7
use FileFetcher\FileFetchingException;
8
9
/**
10
 * Webservice documentation: http://code.google.com/apis/maps/documentation/geocoding/
11
 *
12
 * @since 4.5
13
 *
14
 * @licence GNU GPL v2+
15
 * @author Jeroen De Dauw < [email protected] >
16
 */
17
class GoogleGeocoder implements Geocoder {
18
19
	private $fileFetcher;
20
	private $apiKey;
21
	private $apiVersion;
22
23
	/**
24
	 * @param FileFetcher $fileFetcher
25
	 * @param string $apiKey
26
	 * @param string $apiVersion
27
	 */
28 7
	public function __construct( FileFetcher $fileFetcher, $apiKey, $apiVersion ) {
29 7
		$this->fileFetcher = $fileFetcher;
30 7
		$this->apiKey = $apiKey;
31 7
		$this->apiVersion = $apiVersion;
32 7
	}
33
34
	/**
35
	 * @param string $address
36
	 *
37
	 * @return LatLongValue|null
38
	 */
39 7
	public function geocode( $address ) {
40
		try {
41 7
			$response = $this->fileFetcher->fetchFile( $this->getRequestUrl( $address ) );
42
		}
43 1
		catch ( FileFetchingException $ex ) {
44 1
			return null;
45
		}
46
47 6
		$jsonResponse = json_decode( $response, true );
48
49 6
		if ( !is_array( $jsonResponse ) ) {
50 1
			return null;
51
		}
52
53 5
		if ( !array_key_exists( 'results', $jsonResponse ) || count( $jsonResponse['results'] ) < 1 ) {
54 2
			return null;
55
		}
56
57 3
		$location = @$jsonResponse['results'][0]['geometry']['location'];
58
59 3
		if ( !is_array( $location )
60 3
			 || !array_key_exists( 'lat', $location ) || !array_key_exists( 'lng', $location ) ) {
61 2
			return null;
62
		}
63
64 1
		return new LatLongValue( (float)$location['lat'], (float)$location['lng'] );
65
	}
66
67
	/**
68
	 * @param string $address
69
	 *
70
	 * @return string
71
	 */
72 7
	private function getRequestUrl( $address ) {
73
		$urlArgs = [
74 7
			'address' => $address,
75 7
			'key' => $this->apiKey,
76
		];
77
78 7
		if ( $this->apiVersion !== '' ) {
79
			$urlArgs['v'] = $this->apiVersion;
80
		}
81
82 7
		return 'https://maps.googleapis.com/maps/api/geocode/json?' . http_build_query( $urlArgs );
83
	}
84
85
}
86