Passed
Push — master ( 007090...cd366a )
by Ehsan
01:26
created

Geocoder::geocode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 3
crap 2
1
<?php
2
3
namespace Geocoder;
4
5
class Geocoder
6
{
7
    const API_URL = 'http://maps.google.com/maps/api/geocode';
8
    const VALID_OUTPUT_FORMAT = ['json', 'xml'];
9
10
    /**
11
     * @param        $address
12
     * @param string $region
13
     * @param string $outputFormat
14
     *
15
     * @throws \Exception
16
     *
17
     * @return string
18
     */
19 8
    public function geocode($address, $region = '', $outputFormat = 'json')
20
    {
21 8
        if ($this->validateOutputFormat($outputFormat) !== true) {
22 1
            throw new \Exception("'{$outputFormat}' is not a valid format");
23
        }
24
25 7
        return file_get_contents($this->generateRequestUrl($address, $region, $outputFormat));
26
    }
27
28
    /**
29
     * @param $address
30
     *
31
     * @return array
32
     */
33 3
    public function getLatLng($address)
34
    {
35 3
        $result = $this->geocode($address);
36 3
        $result = json_decode($result, true);
37
38 3
        if ($result['status'] !== 'OK') {
39 1
            return;
40
        }
41
42 2
        $latLng = [];
43 2
        foreach ($result['results'] as $result) {
44 2
            $latLng[] = [
45 2
                'lat' => $result['geometry']['location']['lat'],
46 2
                'lng' => $result['geometry']['location']['lng'],
47
            ];
48
        }
49
50 2
        return $latLng;
51
    }
52
53
    /**
54
     * @param $format
55
     *
56
     * @return bool
57
     */
58 8
    private function validateOutputFormat($format)
59
    {
60 8
        if (in_array($format, self::VALID_OUTPUT_FORMAT)) {
61 7
            return true;
62
        }
63
64 1
        return false;
65
    }
66
67
    /**
68
     * @param        $address
69
     * @param string $region
70
     * @param string $outputFormat
71
     * @param bool   $sensor
72
     *
73
     * @return string
74
     */
75 7
    private function generateRequestUrl($address, $region = '', $outputFormat = 'json', $sensor = false)
76
    {
77 7
        $baseUrl = self::API_URL.'/'.$outputFormat.'?address='.urlencode($address).'&sensor='.$sensor;
78
79 7
        if (!empty($region)) {
80 1
            $baseUrl .= "&region={$region}";
81
        }
82
83 7
        return $baseUrl;
84
    }
85
}
86