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

Geocoder   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 87.5%

Importance

Changes 0
Metric Value
dl 0
loc 80
ccs 21
cts 24
cp 0.875
rs 10
c 0
b 0
f 0
wmc 9
lcom 1
cbo 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A geocode() 0 8 2
A getLatLng() 0 19 3
A validateOutputFormat() 0 8 2
A generateRequestUrl() 0 10 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
     * @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