Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like OptimizelyApiClient often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use OptimizelyApiClient, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
16 | class OptimizelyApiClient |
||
17 | { |
||
|
|||
18 | /** |
||
19 | * Auth credentials. |
||
20 | * @var array |
||
21 | */ |
||
22 | private $authCredentials = array(); |
||
23 | |||
24 | /** |
||
25 | * API version. |
||
26 | * @var string |
||
27 | */ |
||
28 | private $apiVersion; |
||
29 | |||
30 | /** |
||
31 | * CURL handle. |
||
32 | * @var resource |
||
33 | */ |
||
34 | private $curlHandle; |
||
35 | |||
36 | /** |
||
37 | * Debugging information. Typically contains the last HTTP request/response. |
||
38 | * @var type |
||
39 | */ |
||
40 | private $diagnosticsInfo = array(); |
||
41 | |||
42 | /** |
||
43 | * Instantiated services (used internally). |
||
44 | * @var array |
||
45 | */ |
||
46 | private $services = array(); |
||
47 | |||
48 | /** |
||
49 | * Constructor. |
||
50 | * @param array $authCredentials Auth credentials. |
||
51 | * @param string $apiVersion Optional. Currently supported 'v2' only. |
||
52 | */ |
||
53 | 13 | public function __construct($authCredentials, $apiVersion='v2') |
|
72 | |||
73 | /** |
||
74 | * Returns API version (currently it is always 'v2'). |
||
75 | * @return string |
||
76 | */ |
||
77 | 1 | public function getApiVersion() |
|
81 | |||
82 | /** |
||
83 | * Sets API version. |
||
84 | * @param string $apiVersion Currently, 'v2' only. |
||
85 | */ |
||
86 | 9 | public function setApiVersion($apiVersion) |
|
87 | { |
||
88 | 9 | if ($apiVersion!='v2') { |
|
89 | 1 | throw new Exception('Invalid API version passed'); |
|
90 | } |
||
91 | |||
92 | 9 | $this->apiVersion = $apiVersion; |
|
93 | 9 | } |
|
94 | |||
95 | /** |
||
96 | * Returns auth credentials |
||
97 | * @return array |
||
98 | */ |
||
99 | 1 | public function getAuthCredentials() |
|
103 | |||
104 | /** |
||
105 | * Sets Auth credentials. |
||
106 | * @param array $authCredentials |
||
107 | */ |
||
108 | 10 | public function setAuthCredentials($authCredentials) |
|
116 | |||
117 | /** |
||
118 | * Returns access token information as array. |
||
119 | * @return array |
||
120 | */ |
||
121 | 1 | public function getAccessToken() |
|
144 | |||
145 | /** |
||
146 | * Returns refresh token. |
||
147 | * @return string |
||
148 | */ |
||
149 | 2 | public function getRefreshToken() |
|
159 | |||
160 | /** |
||
161 | * Sends an HTTP request to the given URL and returns response in form of array. |
||
162 | * @param string $url The URL of Optimizely endpoint (relative, without host and API version). |
||
163 | * @param array $queryParams The list of query parameters. |
||
164 | * @param string $method HTTP method (GET or POST). |
||
165 | * @param array $postData Data send in request body (only for POST method). |
||
166 | * @return array Optimizely response in form of array. |
||
167 | * @throws Exception |
||
168 | */ |
||
169 | 2 | public function sendApiRequest($url, $queryParams = array(), $method='GET', |
|
184 | |||
185 | /** |
||
186 | * Sends an HTTP request to the given URL and returns response in form of array. |
||
187 | * @param string $url The URL of Optimizely endpoint. |
||
188 | * @param array $queryParams The list of query parameters. |
||
189 | * @param string $method HTTP method (GET or POST). |
||
190 | * @param array $postData Data send in request body (only for POST method). |
||
191 | * @return array Optimizely response in form of array. |
||
192 | * @throws Exception |
||
193 | */ |
||
194 | 2 | private function sendHttpRequest($url, $queryParams = array(), $method='GET', |
|
195 | $postData = array()) |
||
196 | { |
||
197 | // Reset diagnostics info. |
||
198 | 2 | $this->diagnosticsInfo = array(); |
|
199 | |||
200 | // Check if CURL is initialized (it should have been initialized in |
||
201 | // constructor). |
||
202 | 2 | if ($this->curlHandle==false) { |
|
203 | throw new Exception('CURL is not initialized', |
||
204 | Exception::CODE_CURL_ERROR); |
||
205 | } |
||
206 | |||
207 | 2 | if ($method!='GET' && $method!='POST' && $method!='PUT' && |
|
208 | 2 | $method!='PATCH' && $method!='DELETE') { |
|
209 | throw new Exception('Invalid HTTP method passed: ' . $method); |
||
210 | } |
||
211 | |||
212 | 2 | if (!isset($this->authCredentials['access_token'])) { |
|
213 | throw new Exception('OAuth access token is not set. You should pass ' . |
||
214 | 'it to the class constructor when initializing the Optimizely client.'); |
||
215 | } |
||
216 | |||
217 | // Append query parameters to URL. |
||
218 | 2 | if (count($queryParams)!=0) { |
|
219 | $query = http_build_query($queryParams); |
||
220 | $url .= '?' . $query; |
||
221 | } |
||
222 | |||
223 | $headers = array( |
||
224 | 2 | "Authorization: Bearer " . $this->authCredentials['access_token'], |
|
225 | "Content-Type: application/json" |
||
226 | 2 | ); |
|
227 | 2 | $content = ''; |
|
228 | 2 | if (count($postData)!=0) { |
|
229 | $content = json_encode($postData); |
||
230 | } |
||
231 | 2 | $headers[] = "Content-length:" . strlen($content); |
|
232 | |||
233 | // Reset CURL state. |
||
234 | 2 | if (!function_exists('curl_reset')) { |
|
235 | curl_close($this->curlHandle); |
||
236 | $this->curlHandle = curl_init(); |
||
237 | } else { |
||
238 | 2 | curl_reset($this->curlHandle); |
|
239 | } |
||
240 | |||
241 | // Set HTTP options. |
||
242 | 2 | curl_setopt($this->curlHandle, CURLOPT_URL, $url); |
|
243 | 2 | curl_setopt($this->curlHandle, CURLOPT_CUSTOMREQUEST, $method); |
|
244 | 2 | if (count($postData)!=0) { |
|
245 | curl_setopt($this->curlHandle, CURLOPT_POSTFIELDS, $content); |
||
246 | } |
||
247 | 2 | curl_setopt($this->curlHandle, CURLOPT_RETURNTRANSFER, true); |
|
248 | 2 | curl_setopt($this->curlHandle, CURLOPT_HEADER, true); |
|
249 | 2 | curl_setopt($this->curlHandle, CURLOPT_HTTPHEADER, $headers); |
|
250 | 2 | curl_setopt($this->curlHandle, CURLINFO_HEADER_OUT, true); |
|
251 | |||
252 | // Save diagnostics info. |
||
253 | 2 | $this->diagnosticsInfo['request']['method'] = $method; |
|
254 | 2 | $this->diagnosticsInfo['request']['url'] = $url; |
|
255 | 2 | $this->diagnosticsInfo['request']['headers'] = $headers; |
|
256 | 2 | $this->diagnosticsInfo['request']['content'] = $content; |
|
257 | |||
258 | // Execute HTTP request and get response. |
||
259 | 2 | $result = curl_exec($this->curlHandle); |
|
260 | 2 | if ($result === false) { |
|
261 | $code = curl_errno($this->curlHandle); |
||
262 | $error = curl_error($this->curlHandle); |
||
263 | throw new Exception("Failed to send HTTP request $method '$url', " . |
||
264 | "the error code was $code, error message was: '$error'", |
||
265 | Exception::CODE_CURL_ERROR, $code, $error); |
||
266 | } |
||
267 | |||
268 | // Split response headers and body |
||
269 | 2 | $headerSize = curl_getinfo($this->curlHandle, CURLINFO_HEADER_SIZE); |
|
270 | 2 | $headers = substr($result, 0, $headerSize); |
|
271 | 2 | $body = substr($result, $headerSize); |
|
272 | |||
273 | // Parse response headers. |
||
274 | 2 | $headers = explode("\n", $headers); |
|
275 | 2 | $parsedHeaders = array(); |
|
276 | 2 | foreach ($headers as $i=>$header) { |
|
277 | 2 | if ($i==0) |
|
278 | 2 | continue; // Skip first line (http code). |
|
279 | 2 | $pos = strpos($header, ':'); |
|
280 | 2 | if ($pos!=false) { |
|
281 | 2 | $headerName = trim(strtolower(substr($header, 0, $pos))); |
|
282 | 2 | $headerValue = trim(substr($header, $pos+1)); |
|
283 | 2 | $parsedHeaders[$headerName] = $headerValue; |
|
284 | 2 | } |
|
285 | 2 | } |
|
286 | |||
287 | // Get HTTP code. |
||
288 | 2 | $info = curl_getinfo($this->curlHandle); |
|
289 | 2 | $httpCode = $info['http_code']; |
|
290 | |||
291 | // Save diagnostics info. |
||
292 | 2 | $this->diagnosticsInfo['response']['http_code'] = $httpCode; |
|
293 | 2 | $this->diagnosticsInfo['response']['headers'] = $headers; |
|
294 | 2 | $this->diagnosticsInfo['response']['content'] = $body; |
|
295 | |||
296 | // Determine if we have rate limiting headers |
||
297 | 2 | $rateLimit = null; |
|
298 | 2 | $rateLimitRemaining = null; |
|
299 | 2 | $rateLimitReset = null; |
|
300 | 2 | if (isset($parsedHeaders['x-ratelimit-limit'])) { |
|
301 | $rateLimit = $parsedHeaders['x-ratelimit-limit']; |
||
302 | } |
||
303 | |||
304 | 2 | if (isset($parsedHeaders['x-ratelimit-remaining'])) { |
|
305 | $rateLimitRemaining = $parsedHeaders['x-ratelimit-remaining']; |
||
306 | } |
||
307 | |||
308 | 2 | if (isset($parsedHeaders['x-ratelimit-reset'])) { |
|
309 | $rateLimitReset = $parsedHeaders['x-ratelimit-reset']; |
||
310 | } |
||
311 | |||
312 | // JSON-decode payload. |
||
313 | 2 | $decodedPayload = json_decode($body, true); |
|
314 | 2 | if ($decodedPayload===false) { |
|
315 | throw new Exception('Could not JSON-decode the Optimizely API response. Request was ' . |
||
316 | $method . ' "' . $url . '". The response was: "' . $body . '"', |
||
317 | Exception::CODE_API_ERROR, array('http_code'=>$httpCode)); |
||
318 | } |
||
319 | |||
320 | // Check HTTP response code. |
||
321 | 2 | if ($httpCode<200 || $httpCode>299) { |
|
322 | |||
323 | 2 | if (!isset($decodedPayload['message']) || |
|
324 | 1 | !isset($decodedPayload['code']) || |
|
325 | 2 | !isset($decodedPayload['uuid'])) { |
|
326 | 1 | throw new Exception('Optimizely API responded with error code ' . $httpCode . |
|
327 | 1 | '. Request was ' . $method . ' "' . $url . '". Response was "' . $body . '"', |
|
328 | 1 | Exception::CODE_API_ERROR, array( |
|
329 | 1 | 'http_code' => $httpCode, |
|
330 | 1 | 'rate_limit' => $rateLimit, |
|
331 | 1 | 'rate_limit_remaining' => $rateLimitRemaining, |
|
332 | 1 | 'rate_limit_reset' => $rateLimitReset, |
|
333 | 1 | )); |
|
334 | } |
||
335 | |||
336 | //print_r($this->getDiagnosticsInfo()); |
||
337 | |||
338 | 1 | throw new Exception($decodedPayload['message'], Exception::CODE_API_ERROR, |
|
339 | array( |
||
340 | 1 | 'http_code'=>$decodedPayload['code'], |
|
341 | 1 | 'uuid'=>$decodedPayload['uuid'], |
|
342 | 1 | 'rate_limit' => $rateLimit, |
|
343 | 1 | 'rate_limit_remaining' => $rateLimitRemaining, |
|
344 | 'rate_limit_reset' => $rateLimitReset |
||
345 | 1 | )); |
|
346 | } |
||
347 | |||
348 | // Create Result object |
||
349 | $result = new Result($decodedPayload, $httpCode); |
||
350 | $result->setRateLimit($rateLimit); |
||
351 | $result->setRateLimitRemaining($rateLimitRemaining); |
||
352 | $result->setRateLimitReset($rateLimitReset); |
||
353 | |||
354 | // Determine if we have prev/next/last page headers. |
||
355 | if (isset($parsedHeaders['link'])) |
||
356 | { |
||
357 | // Parse LINK header |
||
358 | $matched = preg_match_all('/<(.+)>;\s+rel=(\w+)(,|\z)/U', |
||
359 | $parsedHeaders['link'], $matches, PREG_SET_ORDER); |
||
360 | if (!$matched) { |
||
361 | throw new Exception('Error parsing LINK header: ' . |
||
362 | $parsedHeaders['link'], Exception::CODE_API_ERROR, $httpCode); |
||
363 | } |
||
364 | |||
365 | foreach ($matches as $match) { |
||
366 | |||
367 | $url = $match[1]; |
||
368 | $rel = $match[2]; |
||
369 | |||
370 | $matched = preg_match('/page=(\d+)/U', $url, $pageMatches); |
||
371 | View Code Duplication | if (!$matched || count($pageMatches)!=2) { |
|
372 | throw new Exception('Error extracting page argument while parsing LINK header: ' . |
||
373 | $parsedHeaders['link'], Exception::CODE_API_ERROR, |
||
374 | array('http_code'=>$httpCode)); |
||
375 | } |
||
376 | |||
377 | $pageNumber = $pageMatches[1]; |
||
378 | |||
379 | if ($rel=='prev') { |
||
380 | $result->setPrevPage($pageNumber); |
||
381 | } else if ($rel=='next') { |
||
382 | $result->setNextPage($pageNumber); |
||
383 | View Code Duplication | } else if ($rel=='last') { |
|
384 | $result->setLastPage($pageNumber); |
||
385 | } else { |
||
386 | throw new Exception('Unexpected rel argument while parsing LINK header: ' . |
||
387 | $parsedHeaders['link'], Exception::CODE_API_ERROR, |
||
388 | array('http_code'=>$httpCode)); |
||
389 | } |
||
390 | } |
||
391 | } |
||
392 | |||
393 | // Return the result. |
||
394 | return $result; |
||
395 | } |
||
396 | |||
397 | /** |
||
398 | * Determines whether the access token has expired or not. Returns true if |
||
399 | * token has expired; false if token is valid. |
||
400 | * @return boolean |
||
401 | */ |
||
402 | 2 | private function isAccessTokenExpired() |
|
424 | |||
425 | /** |
||
426 | * This method retrieves the access token by refresh token. |
||
427 | * @return array |
||
428 | * @throw Exception |
||
429 | */ |
||
430 | 1 | private function getAccessTokenByRefreshToken() |
|
462 | |||
463 | /** |
||
464 | * Provides access to API services (experiments, campaigns, etc.) |
||
465 | * @method Audiences audiences() |
||
466 | * @method Campaigns campaigns() |
||
467 | * @method Events events() |
||
468 | * @method Experiment experiments() |
||
469 | * @method Pages pages() |
||
470 | * @method Projects projects() |
||
471 | */ |
||
472 | 1 | public function __call($name, $arguments) |
|
503 | |||
504 | /** |
||
505 | * Returns last HTTP request/response information (for diagnostics/debugging |
||
506 | * purposes): |
||
507 | * - request |
||
508 | * - method |
||
509 | * - headers |
||
510 | * - content |
||
511 | * - response |
||
512 | * - http_code |
||
513 | * - headers |
||
514 | * - content |
||
515 | * @return array |
||
516 | */ |
||
517 | 1 | public function getDiagnosticsInfo() |
|
521 | } |