Total Complexity | 76 |
Total Lines | 641 |
Duplicated Lines | 0 % |
Changes | 0 |
Complex classes like Connection 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.
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 Connection, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
19 | class Connection |
||
20 | { |
||
21 | /** |
||
22 | * @var string |
||
23 | */ |
||
24 | private $baseUrl = 'https://start.exactonline.nl'; |
||
25 | |||
26 | /** |
||
27 | * @var string |
||
28 | */ |
||
29 | private $apiUrl = '/api/v1'; |
||
30 | |||
31 | /** |
||
32 | * @var string |
||
33 | */ |
||
34 | private $authUrl = '/api/oauth2/auth'; |
||
35 | |||
36 | /** |
||
37 | * @var string |
||
38 | */ |
||
39 | private $tokenUrl = '/api/oauth2/token'; |
||
40 | |||
41 | /** |
||
42 | * @var mixed |
||
43 | */ |
||
44 | private $exactClientId; |
||
45 | |||
46 | /** |
||
47 | * @var mixed |
||
48 | */ |
||
49 | private $exactClientSecret; |
||
50 | |||
51 | /** |
||
52 | * @var mixed |
||
53 | */ |
||
54 | private $authorizationCode; |
||
55 | |||
56 | /** |
||
57 | * @var mixed |
||
58 | */ |
||
59 | private $accessToken; |
||
60 | |||
61 | /** |
||
62 | * @var mixed |
||
63 | */ |
||
64 | private $tokenExpires; |
||
65 | |||
66 | /** |
||
67 | * @var mixed |
||
68 | */ |
||
69 | private $refreshToken; |
||
70 | |||
71 | /** |
||
72 | * @var mixed |
||
73 | */ |
||
74 | private $redirectUrl; |
||
75 | |||
76 | /** |
||
77 | * @var mixed |
||
78 | */ |
||
79 | private $division; |
||
80 | |||
81 | /** |
||
82 | * @var Client|null |
||
83 | */ |
||
84 | private $client; |
||
85 | |||
86 | /** |
||
87 | * @var callable(Connection) |
||
88 | */ |
||
89 | private $tokenUpdateCallback; |
||
90 | |||
91 | /** |
||
92 | * @var callable(Connection) |
||
93 | */ |
||
94 | private $acquireAccessTokenLockCallback; |
||
95 | |||
96 | /** |
||
97 | * @var callable(Connection) |
||
98 | */ |
||
99 | private $acquireAccessTokenUnlockCallback; |
||
100 | |||
101 | /** |
||
102 | * @var callable[] |
||
103 | */ |
||
104 | protected $middleWares = []; |
||
105 | |||
106 | /** |
||
107 | * @var string|null |
||
108 | */ |
||
109 | public $nextUrl = null; |
||
110 | |||
111 | /** |
||
112 | * @return Client |
||
113 | */ |
||
114 | private function client() |
||
115 | { |
||
116 | if ($this->client) { |
||
117 | return $this->client; |
||
118 | } |
||
119 | |||
120 | $handlerStack = HandlerStack::create(); |
||
121 | foreach ($this->middleWares as $middleWare) { |
||
122 | $handlerStack->push($middleWare); |
||
123 | } |
||
124 | |||
125 | $this->client = new Client([ |
||
126 | 'http_errors' => true, |
||
127 | 'handler' => $handlerStack, |
||
128 | 'expect' => false, |
||
129 | ]); |
||
130 | |||
131 | return $this->client; |
||
132 | } |
||
133 | |||
134 | public function insertMiddleWare($middleWare) |
||
135 | { |
||
136 | $this->middleWares[] = $middleWare; |
||
137 | } |
||
138 | |||
139 | public function connect() |
||
140 | { |
||
141 | // Redirect for authorization if needed (no access token or refresh token given) |
||
142 | if ($this->needsAuthentication()) { |
||
143 | $this->redirectForAuthorization(); |
||
144 | } |
||
145 | |||
146 | // If access token is not set or token has expired, acquire new token |
||
147 | if (empty($this->accessToken) || $this->tokenHasExpired()) { |
||
148 | $this->acquireAccessToken(); |
||
149 | } |
||
150 | |||
151 | $client = $this->client(); |
||
152 | |||
153 | return $client; |
||
154 | } |
||
155 | |||
156 | /** |
||
157 | * @param string $method |
||
158 | * @param string $endpoint |
||
159 | * @param mixed $body |
||
160 | * @param array $params |
||
161 | * @param array $headers |
||
162 | * @return Request |
||
163 | */ |
||
164 | private function createRequest($method = 'GET', $endpoint, $body = null, array $params = [], array $headers = []) |
||
165 | { |
||
166 | // Add default json headers to the request |
||
167 | $headers = array_merge($headers, [ |
||
168 | 'Accept' => 'application/json', |
||
169 | 'Content-Type' => 'application/json', |
||
170 | 'Prefer' => 'return=representation' |
||
171 | ]); |
||
172 | |||
173 | // If access token is not set or token has expired, acquire new token |
||
174 | if (empty($this->accessToken) || $this->tokenHasExpired()) { |
||
175 | $this->acquireAccessToken(); |
||
176 | } |
||
177 | |||
178 | // If we have a token, sign the request |
||
179 | if (!$this->needsAuthentication() && !empty($this->accessToken)) { |
||
180 | $headers['Authorization'] = 'Bearer ' . $this->accessToken; |
||
181 | } |
||
182 | |||
183 | // Create param string |
||
184 | if (!empty($params)) { |
||
185 | $endpoint .= '?' . http_build_query($params); |
||
186 | } |
||
187 | |||
188 | // Create the request |
||
189 | $request = new Request($method, $endpoint, $headers, $body); |
||
190 | |||
191 | return $request; |
||
192 | } |
||
193 | |||
194 | /** |
||
195 | * @param string $url |
||
196 | * @param array $params |
||
197 | * @param array $headers |
||
198 | * @return mixed |
||
199 | * @throws ApiException |
||
200 | */ |
||
201 | public function get($url, array $params = [], array $headers = []) |
||
202 | { |
||
203 | $url = $this->formatUrl($url, $url !== 'current/Me', $url == $this->nextUrl); |
||
204 | |||
205 | try { |
||
206 | $request = $this->createRequest('GET', $url, null, $params, $headers); |
||
207 | $response = $this->client()->send($request); |
||
208 | |||
209 | return $this->parseResponse($response, $url != $this->nextUrl); |
||
210 | } catch (Exception $e) { |
||
211 | $this->parseExceptionForErrorMessages($e); |
||
212 | } |
||
213 | |||
214 | return null; |
||
215 | } |
||
216 | |||
217 | /** |
||
218 | * @param string $url |
||
219 | * @param mixed $body |
||
220 | * @return mixed |
||
221 | * @throws ApiException |
||
222 | */ |
||
223 | public function post($url, $body) |
||
224 | { |
||
225 | $url = $this->formatUrl($url); |
||
226 | |||
227 | try { |
||
228 | $request = $this->createRequest('POST', $url, $body); |
||
229 | $response = $this->client()->send($request); |
||
230 | |||
231 | return $this->parseResponse($response); |
||
232 | } catch (Exception $e) { |
||
233 | $this->parseExceptionForErrorMessages($e); |
||
234 | } |
||
235 | |||
236 | return null; |
||
237 | } |
||
238 | |||
239 | /** |
||
240 | * @param string $url |
||
241 | * @param mixed $body |
||
242 | * @return mixed |
||
243 | * @throws ApiException |
||
244 | */ |
||
245 | public function put($url, $body) |
||
246 | { |
||
247 | $url = $this->formatUrl($url); |
||
248 | |||
249 | try { |
||
250 | $request = $this->createRequest('PUT', $url, $body); |
||
251 | $response = $this->client()->send($request); |
||
252 | |||
253 | return $this->parseResponse($response); |
||
254 | } catch (Exception $e) { |
||
255 | $this->parseExceptionForErrorMessages($e); |
||
256 | } |
||
257 | |||
258 | return null; |
||
259 | } |
||
260 | |||
261 | /** |
||
262 | * @param string $url |
||
263 | * @return mixed |
||
264 | * @throws ApiException |
||
265 | */ |
||
266 | public function delete($url) |
||
267 | { |
||
268 | $url = $this->formatUrl($url); |
||
269 | |||
270 | try { |
||
271 | $request = $this->createRequest('DELETE', $url); |
||
272 | $response = $this->client()->send($request); |
||
273 | |||
274 | return $this->parseResponse($response); |
||
275 | } catch (Exception $e) { |
||
276 | $this->parseExceptionForErrorMessages($e); |
||
277 | } |
||
278 | |||
279 | return null; |
||
280 | } |
||
281 | |||
282 | /** |
||
283 | * @return string |
||
284 | */ |
||
285 | public function getAuthUrl() |
||
286 | { |
||
287 | return $this->baseUrl . $this->authUrl . '?' . http_build_query(array( |
||
288 | 'client_id' => $this->exactClientId, |
||
289 | 'redirect_uri' => $this->redirectUrl, |
||
290 | 'response_type' => 'code' |
||
291 | )); |
||
292 | } |
||
293 | |||
294 | /** |
||
295 | * @param mixed $exactClientId |
||
296 | */ |
||
297 | public function setExactClientId($exactClientId) |
||
298 | { |
||
299 | $this->exactClientId = $exactClientId; |
||
300 | } |
||
301 | |||
302 | /** |
||
303 | * @param mixed $exactClientSecret |
||
304 | */ |
||
305 | public function setExactClientSecret($exactClientSecret) |
||
306 | { |
||
307 | $this->exactClientSecret = $exactClientSecret; |
||
308 | } |
||
309 | |||
310 | /** |
||
311 | * @param mixed $authorizationCode |
||
312 | */ |
||
313 | public function setAuthorizationCode($authorizationCode) |
||
314 | { |
||
315 | $this->authorizationCode = $authorizationCode; |
||
316 | } |
||
317 | |||
318 | /** |
||
319 | * @param mixed $accessToken |
||
320 | */ |
||
321 | public function setAccessToken($accessToken) |
||
322 | { |
||
323 | $this->accessToken = $accessToken; |
||
324 | } |
||
325 | |||
326 | /** |
||
327 | * @param mixed $refreshToken |
||
328 | */ |
||
329 | public function setRefreshToken($refreshToken) |
||
330 | { |
||
331 | $this->refreshToken = $refreshToken; |
||
332 | } |
||
333 | |||
334 | /** |
||
335 | * |
||
336 | */ |
||
337 | public function redirectForAuthorization() |
||
338 | { |
||
339 | $authUrl = $this->getAuthUrl(); |
||
340 | header('Location: ' . $authUrl); |
||
341 | exit; |
||
342 | } |
||
343 | |||
344 | /** |
||
345 | * @param mixed $redirectUrl |
||
346 | */ |
||
347 | public function setRedirectUrl($redirectUrl) |
||
348 | { |
||
349 | $this->redirectUrl = $redirectUrl; |
||
350 | } |
||
351 | |||
352 | /** |
||
353 | * @return bool |
||
354 | */ |
||
355 | public function needsAuthentication() |
||
356 | { |
||
357 | return empty($this->refreshToken) && empty($this->authorizationCode); |
||
358 | } |
||
359 | |||
360 | /** |
||
361 | * @param Response $response |
||
362 | * @param bool $returnSingleIfPossible |
||
363 | * @return mixed |
||
364 | * @throws ApiException |
||
365 | */ |
||
366 | private function parseResponse(Response $response, $returnSingleIfPossible = true) |
||
367 | { |
||
368 | try { |
||
369 | |||
370 | if ($response->getStatusCode() === 204) { |
||
371 | return []; |
||
372 | } |
||
373 | |||
374 | Psr7\rewind_body($response); |
||
|
|||
375 | $json = json_decode($response->getBody()->getContents(), true); |
||
376 | if (array_key_exists('d', $json)) { |
||
377 | if (array_key_exists('__next', $json['d'])) { |
||
378 | $this->nextUrl = $json['d']['__next']; |
||
379 | } |
||
380 | else { |
||
381 | $this->nextUrl = null; |
||
382 | } |
||
383 | |||
384 | if (array_key_exists('results', $json['d'])) { |
||
385 | if ($returnSingleIfPossible && count($json['d']['results']) == 1) { |
||
386 | return $json['d']['results'][0]; |
||
387 | } |
||
388 | |||
389 | return $json['d']['results']; |
||
390 | } |
||
391 | |||
392 | return $json['d']; |
||
393 | } |
||
394 | |||
395 | return $json; |
||
396 | } catch (\RuntimeException $e) { |
||
397 | throw new ApiException($e->getMessage()); |
||
398 | } |
||
399 | } |
||
400 | |||
401 | /** |
||
402 | * @return mixed |
||
403 | */ |
||
404 | private function getCurrentDivisionNumber() |
||
405 | { |
||
406 | if (empty($this->division)) { |
||
407 | $me = new Me($this); |
||
408 | $this->division = $me->find()->CurrentDivision; |
||
409 | } |
||
410 | |||
411 | return $this->division; |
||
412 | } |
||
413 | |||
414 | /** |
||
415 | * @return mixed |
||
416 | */ |
||
417 | public function getRefreshToken() |
||
418 | { |
||
419 | return $this->refreshToken; |
||
420 | } |
||
421 | |||
422 | /** |
||
423 | * @return mixed |
||
424 | */ |
||
425 | public function getAccessToken() |
||
426 | { |
||
427 | return $this->accessToken; |
||
428 | } |
||
429 | |||
430 | private function acquireAccessToken() |
||
431 | { |
||
432 | // If refresh token not yet acquired, do token request |
||
433 | if (empty($this->refreshToken)) { |
||
434 | $body = [ |
||
435 | 'form_params' => [ |
||
436 | 'redirect_uri' => $this->redirectUrl, |
||
437 | 'grant_type' => 'authorization_code', |
||
438 | 'client_id' => $this->exactClientId, |
||
439 | 'client_secret' => $this->exactClientSecret, |
||
440 | 'code' => $this->authorizationCode |
||
441 | ] |
||
442 | ]; |
||
443 | } else { // else do refresh token request |
||
444 | $body = [ |
||
445 | 'form_params' => [ |
||
446 | 'refresh_token' => $this->refreshToken, |
||
447 | 'grant_type' => 'refresh_token', |
||
448 | 'client_id' => $this->exactClientId, |
||
449 | 'client_secret' => $this->exactClientSecret, |
||
450 | ] |
||
451 | ]; |
||
452 | } |
||
453 | |||
454 | |||
455 | try { |
||
456 | if (is_callable($this->acquireAccessTokenLockCallback)) { |
||
457 | call_user_func($this->acquireAccessTokenLockCallback, $this); |
||
458 | } |
||
459 | |||
460 | $response = $this->client()->post($this->getTokenUrl(), $body); |
||
461 | |||
462 | Psr7\rewind_body($response); |
||
463 | $body = json_decode($response->getBody()->getContents(), true); |
||
464 | |||
465 | if (json_last_error() === JSON_ERROR_NONE) { |
||
466 | $this->accessToken = $body['access_token']; |
||
467 | $this->refreshToken = $body['refresh_token']; |
||
468 | $this->tokenExpires = $this->getDateTimeFromExpires($body['expires_in']); |
||
469 | |||
470 | if (is_callable($this->tokenUpdateCallback)) { |
||
471 | call_user_func($this->tokenUpdateCallback, $this); |
||
472 | } |
||
473 | } else { |
||
474 | throw new ApiException('Could not acquire tokens, json decode failed. Got response: ' . $response->getBody()->getContents()); |
||
475 | } |
||
476 | } catch (BadResponseException $ex) { |
||
477 | throw new ApiException('Could not acquire or refresh tokens [http ' . $ex->getResponse()->getStatusCode() . ']', 0, $ex); |
||
478 | } finally { |
||
479 | if (is_callable($this->acquireAccessTokenUnlockCallback)) { |
||
480 | call_user_func($this->acquireAccessTokenUnlockCallback, $this); |
||
481 | } |
||
482 | } |
||
483 | } |
||
484 | |||
485 | private function getDateTimeFromExpires($expires) |
||
486 | { |
||
487 | if (!is_numeric($expires)) { |
||
488 | throw new \InvalidArgumentException('Function requires a numeric expires value'); |
||
489 | } |
||
490 | |||
491 | return time() + 600; |
||
492 | } |
||
493 | |||
494 | /** |
||
495 | * @return mixed |
||
496 | */ |
||
497 | public function getTokenExpires() |
||
498 | { |
||
499 | return $this->tokenExpires; |
||
500 | } |
||
501 | |||
502 | /** |
||
503 | * @param mixed $tokenExpires |
||
504 | */ |
||
505 | public function setTokenExpires($tokenExpires) |
||
506 | { |
||
507 | $this->tokenExpires = $tokenExpires; |
||
508 | } |
||
509 | |||
510 | private function tokenHasExpired() |
||
511 | { |
||
512 | if (empty($this->tokenExpires)) { |
||
513 | return true; |
||
514 | } |
||
515 | |||
516 | return $this->tokenExpires <= time() + 10; |
||
517 | } |
||
518 | |||
519 | private function formatUrl($endPoint, $includeDivision = true, $formatNextUrl = false) |
||
520 | { |
||
521 | if ($formatNextUrl) { |
||
522 | return $endPoint; |
||
523 | } |
||
524 | |||
525 | if ($includeDivision) { |
||
526 | return implode('/', [ |
||
527 | $this->getApiUrl(), |
||
528 | $this->getCurrentDivisionNumber(), |
||
529 | $endPoint |
||
530 | ]); |
||
531 | } |
||
532 | |||
533 | return implode('/', [ |
||
534 | $this->getApiUrl(), |
||
535 | $endPoint |
||
536 | ]); |
||
537 | } |
||
538 | |||
539 | |||
540 | /** |
||
541 | * @return mixed |
||
542 | */ |
||
543 | public function getDivision() |
||
544 | { |
||
545 | return $this->division; |
||
546 | } |
||
547 | |||
548 | |||
549 | /** |
||
550 | * @param mixed $division |
||
551 | */ |
||
552 | public function setDivision($division) |
||
553 | { |
||
554 | $this->division = $division; |
||
555 | } |
||
556 | |||
557 | /** |
||
558 | * @param callable $callback |
||
559 | */ |
||
560 | public function setAcquireAccessTokenLockCallback($callback) { |
||
561 | $this->acquireAccessTokenLockCallback = $callback; |
||
562 | } |
||
563 | |||
564 | /** |
||
565 | * @param callable $callback |
||
566 | */ |
||
567 | public function setAcquireAccessTokenUnlockCallback($callback) { |
||
568 | $this->acquireAccessTokenUnlockCallback = $callback; |
||
569 | } |
||
570 | |||
571 | /** |
||
572 | * @param callable $callback |
||
573 | */ |
||
574 | public function setTokenUpdateCallback($callback) { |
||
575 | $this->tokenUpdateCallback = $callback; |
||
576 | } |
||
577 | |||
578 | /** |
||
579 | * Parse the reponse in the Exception to return the Exact error messages |
||
580 | * @param Exception $e |
||
581 | * @throws ApiException |
||
582 | */ |
||
583 | private function parseExceptionForErrorMessages(Exception $e) |
||
584 | { |
||
585 | if (! $e instanceof BadResponseException) { |
||
586 | throw new ApiException($e->getMessage()); |
||
587 | } |
||
588 | |||
589 | $response = $e->getResponse(); |
||
590 | Psr7\rewind_body($response); |
||
591 | $responseBody = $response->getBody()->getContents(); |
||
592 | $decodedResponseBody = json_decode($responseBody, true); |
||
593 | |||
594 | if (! is_null($decodedResponseBody) && isset($decodedResponseBody['error']['message']['value'])) { |
||
595 | $errorMessage = $decodedResponseBody['error']['message']['value']; |
||
596 | } else { |
||
597 | $errorMessage = $responseBody; |
||
598 | } |
||
599 | |||
600 | throw new ApiException('Error ' . $response->getStatusCode() .': ' . $errorMessage); |
||
601 | } |
||
602 | |||
603 | /** |
||
604 | * @return string |
||
605 | */ |
||
606 | protected function getBaseUrl() |
||
607 | { |
||
608 | return $this->baseUrl; |
||
609 | } |
||
610 | |||
611 | /** |
||
612 | * @return string |
||
613 | */ |
||
614 | private function getApiUrl() |
||
615 | { |
||
616 | return $this->baseUrl . $this->apiUrl; |
||
617 | } |
||
618 | |||
619 | /** |
||
620 | * @return string |
||
621 | */ |
||
622 | private function getTokenUrl() |
||
623 | { |
||
624 | return $this->baseUrl . $this->tokenUrl; |
||
625 | } |
||
626 | |||
627 | /** |
||
628 | * Set base URL for different countries according to |
||
629 | * https://developers.exactonline.com/#Exact%20Online%20sites.html |
||
630 | * |
||
631 | * @param string $baseUrl |
||
632 | */ |
||
633 | public function setBaseUrl($baseUrl) |
||
636 | } |
||
637 | |||
638 | /** |
||
639 | * @param string $apiUrl |
||
640 | */ |
||
641 | public function setApiUrl($apiUrl) |
||
642 | { |
||
643 | $this->apiUrl = $apiUrl; |
||
644 | } |
||
645 | |||
646 | /** |
||
647 | * @param string $authUrl |
||
648 | */ |
||
649 | public function setAuthUrl($authUrl) |
||
650 | { |
||
651 | $this->authUrl = $authUrl; |
||
652 | } |
||
653 | |||
654 | /** |
||
655 | * @param string $tokenUrl |
||
656 | */ |
||
657 | public function setTokenUrl($tokenUrl) |
||
658 | { |
||
659 | $this->tokenUrl = $tokenUrl; |
||
660 | } |
||
661 | } |
||
662 |