Completed
Push — master ( 329814...199903 )
by Johnny
01:28
created

CalculateDistance::getApiUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
1
<?php
2
namespace Redbox\Distance;
3
4
class CalculateDistance
5
{
6
    const MAPS_DISTANCE_MATRIX_API_URL = 'https://maps.googleapis.com/maps/api/distancematrix/json';
7
    const KM_TO_MILES_CONVERTER       = 0.62137;
8
    const KM_TO_YARD_CONVERTER        = 1093.6133;
9
    const CURRENT_VERSION             = '1.0';
10
    const USER_AGENT                  = 'Calculate Distance V';
11
12
    protected $source                 = '';
13
    protected $destination            = '';
14
    protected $googleAPIkey           = '';
15
    protected $urlOptions             = [];
16
    protected $disable_ssl_verifier   = true;
17
    protected $api_url                = '';
18
19
    /**
20
     * CalculateDistance constructor.
21 12
     */
22 12
    public function __construct() {
23 12
        $this->urlOptions = array(
24 12
            'origins'       => '',
25 12
            'destinations'  => '',
26 12
            'mode'          => 'driving',
27 12
            'language'      => 'en-EN',
28 12
            'sensor'        => 'false',
29
            'key'           => '',
30 12
        );
31
        $this->setApiUrl(self::MAPS_DISTANCE_MATRIX_API_URL);
32
    }
33
34
    /**
35
     * Set the ApiUrl
36
     *
37
     * @param string $api_url
38
     * @return $this
39
     */
40
    public function setApiUrl($api_url)
41
    {
42
        $this->api_url = $api_url;
43
        return $this;
44
    }
45
46 12
    /**
47
     * This is not required as the documentation states but if it becomes required
48 12
     * you can set it with this function.
49 12
     *
50
     * @param $googleAPIkey
51
     * @return $this
52
     */
53
    public function setGoogleAPIkey($googleAPIkey)
54
    {
55
        $this->googleAPIkey = $googleAPIkey;
56 12
        return $this;
57
    }
58 12
59 12
    /**
60
     * Should we use SSL Verifier (Curl) yes or no.
61
     *
62
     * @param $disable_ssl_verifier
63
     * @return $this
64
     */
65
    public function setUseSslVerifier($disable_ssl_verifier)
66 12
    {
67
        $this->disable_ssl_verifier = $disable_ssl_verifier;
68 12
        return $this;
69 12
    }
70
71
    /**
72
     * Set the destination.
73
     *
74
     * @param string $destination
75 12
     * @return $this
76
     */
77 12
    public function setDestination($destination)
78
    {
79
        $this->destination = $destination;
80
        return $this;
81
    }
82
83 12
    /**
84
     * Set the source.
85 12
     *
86
     * @param $source
87
     * @return $this
88
     */
89
    public function setSource($source)
90
    {
91 12
        $this->source = $source;
92
        return $this;
93 12
    }
94
95
    /**
96
     * Return the destination.
97
     *
98
     * @return string
99 12
     */
100
    private function getDestination()
101 12
    {
102
        return $this->destination;
103
    }
104
105
    /**
106
     * Get the API Url.
107 12
     *
108
     * @return string
109 12
     */
110
    public function getApiUrl()
111
    {
112
        return $this->api_url;
113
    }
114
115
    /**
116 12
     * Are we using SSL verifier?
117 12
     *
118 12
     * @return bool
119 12
     */
120 12
    private function useSslVerifier()
121 12
    {
122 12
        return $this->disable_ssl_verifier;
123 12
    }
124 12
125 12
    /**
126
     * Return the source.
127
     *
128
     * @return string
129
     */
130
    private function getSource()
131 12
    {
132
        return $this->source;
133 12
    }
134 12
135 12
    /**
136 12
     * Return the url options.
137
     *
138 12
     * @return array
139 12
     */
140 12
    private function getUrlOptions()
141 12
    {
142 12
        return $this->urlOptions;
143 12
    }
144 12
145 12
    /**
146 12
     * Execute the request to Google Services.
147
     *
148 12
     * @param string $url
149 12
     * @return mixed
150
     */
151 12
    private function requestData($url="")
152 12
    {
153
        $curl = curl_init();
154 12
        curl_setopt_array($curl, array(
155 12
            CURLOPT_RETURNTRANSFER => 1,
156 12
            CURLOPT_URL => $url,
157 12
            CURLOPT_USERAGENT => self::USER_AGENT.self::CURRENT_VERSION,
158 12
        ));
159
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, $this->useSslVerifier());
160
        $resp = curl_exec($curl);
161
        return $resp;
162
    }
163
164
    /**
165
     * Query the distance from Google Services.
166
     *
167 12
     * @return mixed|null
168 12
     */
169 12
    private function calculateDistance()
170 12
    {
171 12
172
        $data                 = $this->getUrlOptions();
173
        $data['origins']      = urlencode($this->getSource());
174
        $data['destinations'] = urlencode($this->getDestination());
175
        $data['key']          = $this->googleAPIkey;
176
177
        $request_string = '';
178
        $cnt = 0;
179
        foreach($data as $key => $val) {
180
            $request_string .= (($cnt > 0) ? '&' : ''). $key.'='.$val;
181
            $cnt++;
182
        }
183 4
184 4
        $url = $this->getApiUrl().'?' . $request_string;
185
        $response = $this->requestData($url);
186
187
        $response = utf8_encode($response);
188
        $route = json_decode($response);
189
190 4
        if ($route && ($rows = current($route->rows))) {
191 4
            $elements = current($rows->elements);
192
            return $elements;
193
        }
194
        return NULL;
195
    }
196
197
    /**
198 8
     * Return the distance calculated to Kilometers.
199 8
     *
200 8
     * @return float|int
201 8
     */
202
    public function getDistanceInKM()
203
    {
204
        $route = $this->calculateDistance();
205
        if( is_null($route) === FALSE) {
206
            if(isset($route->distance->value)){
207
                return round($route->distance->value/1000);
208
            }
209
        }
210
        return -1;
211
    }
212
213
    /**
214
     * Return the distance calculated to Miles.
215
     *
216
     * @return float|int
217
     */
218
    public function getDistanceInMiles()
219
    {
220
        return $this->convertResult(self::KM_TO_MILES_CONVERTER);
221
    }
222
223
    /**
224
     * Return the distance calculated to Yards.
225
     *
226
     * @return float|int
227
     */
228
    public function getDistanceInYards()
229
    {
230
        return $this->convertResult(self::KM_TO_YARD_CONVERTER);
231
    }
232
233
    /**
234
     * This function will do the sum and calculate the distance correctly.
235
     *
236
     * @param $type
237
     * @return float|int
238
     */
239
    private function convertResult($type)
240
    {
241
        $result = $this->getDistanceInKM();
242
        if ($result > -1) {
243
            return ($result * $type);
244
        }
245
        return $result;
246
    }
247
}