Completed
Branch master (199903)
by Johnny
27:19
created

CalculateDistance::setApiUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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