Completed
Push — master ( 08901e...172451 )
by Jeroen
11s
created

Geolocation::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 9
rs 9.6666
cc 2
eloc 5
nc 2
nop 2
1
<?php
2
3
namespace JeroenDesloovere\Geolocation;
4
5
/**
6
 * Geolocation
7
 *
8
 * Get latitude/longitude or address using Google Maps API
9
 *
10
 * @author Jeroen Desloovere <[email protected]>
11
 */
12
class Geolocation
13
{
14
    // API URL
15
    const API_URL = 'maps.googleapis.com/maps/api/geocode/json';
16
17
    private $api_key;
18
    private $https;
19
20
    public function __construct($api_key = null, $https = false)
21
    {
22
        $this->https = $https;
23
24
        if ($api_key) {
25
            $this->api_key = $api_key;
26
            $this->https = true;
27
        }
28
    }
29
30
    /**
31
     * Do call
32
     *
33
     * @return object
34
     * @param  array  $parameters
35
     */
36
    protected function doCall($parameters = array())
37
    {
38
        // check if curl is available
39
        if (!function_exists('curl_init')) {
40
            // throw error
41
            throw new GeolocationException('This method requires cURL (http://php.net/curl), it seems like the extension isn\'t installed.');
42
        }
43
44
        // define url
45
        $url = ($this->https ? 'https://' : 'http://') . self::API_URL . '?';
46
47
        // add every parameter to the url
48
        foreach ($parameters as $key => $value) $url .= $key . '=' . urlencode($value) . '&';
49
50
        // trim last &
51
        $url = trim($url, '&');
52
53
        if ($this->api_key) {
54
            $url .= '&key=' . $this->api_key;
55
        }
56
57
        // init curl
58
        $curl = curl_init();
59
60
        // set options
61
        curl_setopt($curl, CURLOPT_URL, $url);
62
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
63
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
64
        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
65
66
        // execute
67
        $response = curl_exec($curl);
68
69
        // fetch errors
70
        $errorNumber = curl_errno($curl);
71
        $errorMessage = curl_error($curl);
72
73
        // close curl
74
        curl_close($curl);
75
76
        // we have errors
77
        if ($errorNumber != '') throw new GeolocationException($errorMessage);
78
79
        // redefine response as json decoded
80
        $response = json_decode($response);
81
82
        // return the content
83
        return $response->results;
84
    }
85
86
    /**
87
     * Get address using latitude/longitude
88
     *
89
     * @return array(label, components)
0 ignored issues
show
Documentation introduced by
The doc-type array(label, could not be parsed: Expected "|" or "end of type", but got "(" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
90
     * @param  float        $latitude
91
     * @param  float        $longitude
92
     */
93
    public function getAddress($latitude, $longitude)
94
    {
95
        $addressSuggestions = $this->getAddresses($latitude, $longitude);
96
97
        return $addressSuggestions[0];
98
    }
99
100
    /**
101
     * Get possible addresses using latitude/longitude
102
     *
103
     * @return array(label, street, streetNumber, city, cityLocal, zip, country, countryLabel)
0 ignored issues
show
Documentation introduced by
The doc-type array(label, could not be parsed: Expected "|" or "end of type", but got "(" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
104
     * @param  float        $latitude
105
     * @param  float        $longitude
106
     */
107
    public function getAddresses($latitude, $longitude)
108
    {
109
        // init results
110
        $addresses = array();
111
112
        // define result
113
        $addressSuggestions = $this->doCall(array(
114
            'latlng' => $latitude . ',' . $longitude,
115
            'sensor' => 'false'
116
        ));
117
118
        // loop addresses
119
        foreach ($addressSuggestions as $key => $addressSuggestion) {
120
            // init address
121
            $address = array();
122
123
            // define label
124
            $address['label'] = isset($addressSuggestion->formatted_address) ?
125
                $addressSuggestion->formatted_address : null
126
            ;
127
128
            // define address components by looping all address components
129
            foreach ($addressSuggestion->address_components as $component) {
130
                $address['components'][] = array(
131
                    'long_name' => $component->long_name,
132
                    'short_name' => $component->short_name,
133
                    'types' => $component->types
134
                );
135
            }
136
137
            $addresses[$key] = $address;
138
        }
139
140
        return $addresses;
141
    }
142
143
    /**
144
     * Get coordinates latitude/longitude
145
     *
146
     * @return array  The latitude/longitude coordinates
147
     * @param  string $street[optional]
0 ignored issues
show
Documentation introduced by
There is no parameter named $street[optional]. Did you maybe mean $street?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
148
     * @param  string $streetNumber[optional]
0 ignored issues
show
Documentation introduced by
There is no parameter named $streetNumber[optional]. Did you maybe mean $street?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
149
     * @param  string $city[optional]
0 ignored issues
show
Bug introduced by
There is no parameter named $city[optional]. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
150
     * @param  string $zip[optional]
0 ignored issues
show
Bug introduced by
There is no parameter named $zip[optional]. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
151
     * @param  string $country[optional]
0 ignored issues
show
Documentation introduced by
There is no parameter named $country[optional]. Did you maybe mean $country?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
152
     */
153
    public function getCoordinates(
154
        $street = null,
155
        $streetNumber = null,
156
        $city = null,
157
        $zip = null,
158
        $country = null
159
    ) {
160
        // init item
161
        $item = array();
162
163
        // add street
164
        if (!empty($street)) $item[] = $street;
165
166
        // add street number
167
        if (!empty($streetNumber)) $item[] = $streetNumber;
168
169
        // add city
170
        if (!empty($city)) $item[] = $city;
171
172
        // add zip
173
        if (!empty($zip)) $item[] = $zip;
174
175
        // add country
176
        if (!empty($country)) $item[] = $country;
177
178
        // define value
179
        $address = implode(' ', $item);
180
181
        // define result
182
        $results = $this->doCall(array(
183
            'address' => $address,
184
            'sensor' => 'false'
185
        ));
186
187
        // return coordinates latitude/longitude
188
        return array(
189
            'latitude' => array_key_exists(0, $results) ? (float) $results[0]->geometry->location->lat : null,
190
            'longitude' => array_key_exists(0, $results) ? (float) $results[0]->geometry->location->lng : null
191
        );
192
    }
193
}
194
195
/**
196
 * Geolocation Exception
197
 *
198
 * @author Jeroen Desloovere <[email protected]>
199
 */
200
class GeolocationException extends \Exception {}
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class should be in its own file to aid autoloaders.

Having each class in a dedicated file usually plays nice with PSR autoloaders and is therefore a well established practice. If you use other autoloaders, you might not want to follow this rule.

Loading history...
201