Completed
Push — master ( f9f049...9b2260 )
by Ehsan
10:40
created

Geocoder::generateRequestUrl()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

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