Completed
Pull Request — master (#378)
by
unknown
06:27 queued 04:40
created

Connection::insertMiddleWare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
namespace Picqer\Financials\Exact;
4
5
use Exception;
6
use GuzzleHttp\Client;
7
use GuzzleHttp\Exception\BadResponseException;
8
use GuzzleHttp\HandlerStack;
9
use GuzzleHttp\Psr7;
10
use GuzzleHttp\Psr7\Request;
11
use GuzzleHttp\Psr7\Response;
12
13
/**
14
 * Class Connection.
15
 */
16
class Connection
17
{
18
    /**
19
     * @var string
20
     */
21
    private $baseUrl = 'https://start.exactonline.nl';
22
23
    /**
24
     * @var string
25
     */
26
    private $apiUrl = '/api/v1';
27
28
    /**
29
     * @var string
30
     */
31
    private $authUrl = '/api/oauth2/auth';
32
33
    /**
34
     * @var string
35
     */
36
    private $tokenUrl = '/api/oauth2/token';
37
38
    /**
39
     * @var mixed
40
     */
41
    private $exactClientId;
42
43
    /**
44
     * @var mixed
45
     */
46
    private $exactClientSecret;
47
48
    /**
49
     * @var mixed
50
     */
51
    private $authorizationCode;
52
53
    /**
54
     * @var mixed
55
     */
56
    private $accessToken;
57
58
    /**
59
     * @var int the Unix timestamp at which the access token expires
60
     */
61
    private $tokenExpires;
62
63
    /**
64
     * @var mixed
65
     */
66
    private $refreshToken;
67
68
    /**
69
     * @var mixed
70
     */
71
    private $redirectUrl;
72
73
    /**
74
     * @var mixed
75
     */
76
    private $division;
77
78
    /**
79
     * @var Client|null
80
     */
81
    private $client;
82
83
    /**
84
     * @var callable(Connection)
85
     */
86
    private $tokenUpdateCallback;
87
88
    /**
89
     * @var callable(Connection)
90
     */
91
    private $acquireAccessTokenLockCallback;
92
93
    /**
94
     * @var callable(Connection)
95
     */
96
    private $acquireAccessTokenUnlockCallback;
97
98
    /**
99
     * @var callable[]
100
     */
101
    protected $middleWares = [];
102
103
    /**
104
     * @var string|null
105
     */
106
    public $nextUrl = null;
107
108
    /**
109
     * @var int|null
110
     */
111
    protected $dailyLimit;
112
113
    /**
114
     * @var int|null
115
     */
116
    protected $dailyLimitRemaining;
117
118
    /**
119
     * @var int|null
120
     */
121
    protected $dailyLimitReset;
122
123
    /**
124
     * @var int|null
125
     */
126
    protected $minutelyLimit;
127
128
    /**
129
     * @var int|null
130
     */
131
    protected $minutelyLimitRemaining;
132
133
    /**
134
     * @return Client
135
     */
136
    private function client()
137
    {
138
        if ($this->client) {
139
            return $this->client;
140
        }
141
142
        $handlerStack = HandlerStack::create();
143
        foreach ($this->middleWares as $middleWare) {
144
            $handlerStack->push($middleWare);
145
        }
146
147
        $this->client = new Client([
148
            'http_errors' => true,
149
            'handler'     => $handlerStack,
150
            'expect'      => false,
151
        ]);
152
153
        return $this->client;
154
    }
155
156
    public function insertMiddleWare($middleWare)
157
    {
158
        $this->middleWares[] = $middleWare;
159
    }
160
161
    public function connect()
162
    {
163
        // Redirect for authorization if needed (no access token or refresh token given)
164
        if ($this->needsAuthentication()) {
165
            $this->redirectForAuthorization();
166
        }
167
168
        // If access token is not set or token has expired, acquire new token
169
        if (empty($this->accessToken) || $this->tokenHasExpired()) {
170
            $this->acquireAccessToken();
171
        }
172
173
        $client = $this->client();
174
175
        return $client;
176
    }
177
178
    /**
179
     * @param string $method
180
     * @param string $endpoint
181
     * @param mixed  $body
182
     * @param array  $params
183
     * @param array  $headers
184
     *
185
     * @return Request
186
     */
187
    private function createRequest($method, $endpoint, $body = null, array $params = [], array $headers = [])
188
    {
189
        // Add default json headers to the request
190
        $headers = array_merge($headers, [
191
            'Accept'       => 'application/json',
192
            'Content-Type' => 'application/json',
193
            'Prefer'       => 'return=representation',
194
        ]);
195
196
        // If access token is not set or token has expired, acquire new token
197
        if (empty($this->accessToken) || $this->tokenHasExpired()) {
198
            $this->acquireAccessToken();
199
        }
200
201
        // If we have a token, sign the request
202
        if (! $this->needsAuthentication() && ! empty($this->accessToken)) {
203
            $headers['Authorization'] = 'Bearer ' . $this->accessToken;
204
        }
205
206
        // Create param string
207
        if (! empty($params)) {
208
            $endpoint .= '?' . http_build_query($params);
209
        }
210
211
        // Create the request
212
        $request = new Request($method, $endpoint, $headers, $body);
213
214
        return $request;
215
    }
216
217
    /**
218
     * @param string $url
219
     * @param array  $params
220
     * @param array  $headers
221
     *
222
     * @throws ApiException
223
     *
224
     * @return mixed
225
     */
226
    public function get($url, array $params = [], array $headers = [])
227
    {
228
        $url = $this->formatUrl($url, $url !== 'current/Me', $url == $this->nextUrl);
229
230
        try {
231
            $request = $this->createRequest('GET', $url, null, $params, $headers);
232
            $response = $this->client()->send($request);
233
234
            return $this->parseResponse($response, $url != $this->nextUrl);
235
        } catch (Exception $e) {
236
            $this->parseExceptionForErrorMessages($e);
237
        }
238
    }
239
240
    /**
241
     * @param string $url
242
     * @param mixed  $body
243
     *
244
     * @throws ApiException
245
     *
246
     * @return mixed
247
     */
248
    public function post($url, $body)
249
    {
250
        $url = $this->formatUrl($url);
251
252
        try {
253
            $request = $this->createRequest('POST', $url, $body);
254
            $response = $this->client()->send($request);
255
256
            return $this->parseResponse($response);
257
        } catch (Exception $e) {
258
            $this->parseExceptionForErrorMessages($e);
259
        }
260
    }
261
262
    /**
263
     * @param string $url
264
     * @param mixed  $body
265
     *
266
     * @throws ApiException
267
     *
268
     * @return mixed
269
     */
270
    public function put($url, $body)
271
    {
272
        $url = $this->formatUrl($url);
273
274
        try {
275
            $request = $this->createRequest('PUT', $url, $body);
276
            $response = $this->client()->send($request);
277
278
            return $this->parseResponse($response);
279
        } catch (Exception $e) {
280
            $this->parseExceptionForErrorMessages($e);
281
        }
282
    }
283
284
    /**
285
     * @param string $url
286
     *
287
     * @throws ApiException
288
     *
289
     * @return mixed
290
     */
291
    public function delete($url)
292
    {
293
        $url = $this->formatUrl($url);
294
295
        try {
296
            $request = $this->createRequest('DELETE', $url);
297
            $response = $this->client()->send($request);
298
299
            return $this->parseResponse($response);
300
        } catch (Exception $e) {
301
            $this->parseExceptionForErrorMessages($e);
302
        }
303
    }
304
305
    /**
306
     * @return string
307
     */
308
    public function getAuthUrl()
309
    {
310
        return $this->baseUrl . $this->authUrl . '?' . http_build_query([
311
            'client_id'     => $this->exactClientId,
312
            'redirect_uri'  => $this->redirectUrl,
313
            'response_type' => 'code',
314
        ]);
315
    }
316
317
    /**
318
     * @param mixed $exactClientId
319
     */
320
    public function setExactClientId($exactClientId)
321
    {
322
        $this->exactClientId = $exactClientId;
323
    }
324
325
    /**
326
     * @param mixed $exactClientSecret
327
     */
328
    public function setExactClientSecret($exactClientSecret)
329
    {
330
        $this->exactClientSecret = $exactClientSecret;
331
    }
332
333
    /**
334
     * @param mixed $authorizationCode
335
     */
336
    public function setAuthorizationCode($authorizationCode)
337
    {
338
        $this->authorizationCode = $authorizationCode;
339
    }
340
341
    /**
342
     * @param mixed $accessToken
343
     */
344
    public function setAccessToken($accessToken)
345
    {
346
        $this->accessToken = $accessToken;
347
    }
348
349
    /**
350
     * @param mixed $refreshToken
351
     */
352
    public function setRefreshToken($refreshToken)
353
    {
354
        $this->refreshToken = $refreshToken;
355
    }
356
357
    public function redirectForAuthorization()
358
    {
359
        $authUrl = $this->getAuthUrl();
360
        header('Location: ' . $authUrl);
361
        exit;
362
    }
363
364
    /**
365
     * @param mixed $redirectUrl
366
     */
367
    public function setRedirectUrl($redirectUrl)
368
    {
369
        $this->redirectUrl = $redirectUrl;
370
    }
371
372
    /**
373
     * @return bool
374
     */
375
    public function needsAuthentication()
376
    {
377
        return empty($this->refreshToken) && empty($this->authorizationCode);
378
    }
379
380
    /**
381
     * @param mixed $data
382
     *
383
     * @return mixed
384
     */
385
    private function parseJsonDates($data)
386
    {
387
        array_walk_recursive($data, function (&$item, $key) {
388
            $matches = null;
389
            if (preg_match('/\/Date\((\d+)\)\//', $item, $matches)) {
390
                $microtime = ((int) $matches[1]) / 1000;
391
                if ($microtime == ((int) $microtime)) {
392
                    $microtime = "$microtime.000";
393
                } else {
394
                    $microtime = "$microtime";
395
                }
396
                $date = \DateTime::createFromFormat('U.u', $microtime);
397
                $date->setTimezone(new \DateTimeZone('UTC'));
398
                $item = $date->format('Y-m-d\TH:i:s.u');
399
            }
400
        });
401
402
        return $data;
403
    }
404
405
    /**
406
     * @param Response $response
407
     * @param bool     $returnSingleIfPossible
408
     *
409
     * @throws ApiException
410
     *
411
     * @return mixed
412
     */
413
    private function parseResponse(Response $response, $returnSingleIfPossible = true)
414
    {
415
        try {
416
            if ($response->getStatusCode() === 204) {
417
                return [];
418
            }
419
420
            $this->extractRateLimits($response);
421
422
            Psr7\rewind_body($response);
0 ignored issues
show
Bug introduced by
The function rewind_body was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

422
            /** @scrutinizer ignore-call */ 
423
            Psr7\rewind_body($response);
Loading history...
423
            $json = $this->parseJsonDates(json_decode($response->getBody()->getContents(), true));
424
            if (array_key_exists('d', $json)) {
425
                if (array_key_exists('__next', $json['d'])) {
426
                    $this->nextUrl = $json['d']['__next'];
427
                } else {
428
                    $this->nextUrl = null;
429
                }
430
431
                if (array_key_exists('results', $json['d'])) {
432
                    if ($returnSingleIfPossible && count($json['d']['results']) == 1) {
433
                        return $json['d']['results'][0];
434
                    }
435
436
                    return $json['d']['results'];
437
                }
438
439
                return $json['d'];
440
            }
441
442
            return $json;
443
        } catch (\RuntimeException $e) {
444
            throw new ApiException($e->getMessage());
445
        }
446
    }
447
448
    /**
449
     * @return mixed
450
     */
451
    private function getCurrentDivisionNumber()
452
    {
453
        if (empty($this->division)) {
454
            $me = new Me($this);
455
            $this->division = $me->find()->CurrentDivision;
456
        }
457
458
        return $this->division;
459
    }
460
461
    /**
462
     * @return mixed
463
     */
464
    public function getRefreshToken()
465
    {
466
        return $this->refreshToken;
467
    }
468
469
    /**
470
     * @return mixed
471
     */
472
    public function getAccessToken()
473
    {
474
        return $this->accessToken;
475
    }
476
477
    private function acquireAccessToken()
478
    {
479
        // If refresh token not yet acquired, do token request
480
        if (empty($this->refreshToken)) {
481
            $body = [
482
                'form_params' => [
483
                    'redirect_uri'  => $this->redirectUrl,
484
                    'grant_type'    => 'authorization_code',
485
                    'client_id'     => $this->exactClientId,
486
                    'client_secret' => $this->exactClientSecret,
487
                    'code'          => $this->authorizationCode,
488
                ],
489
            ];
490
        } else { // else do refresh token request
491
            $body = [
492
                'form_params' => [
493
                    'refresh_token' => $this->refreshToken,
494
                    'grant_type'    => 'refresh_token',
495
                    'client_id'     => $this->exactClientId,
496
                    'client_secret' => $this->exactClientSecret,
497
                ],
498
            ];
499
        }
500
501
        try {
502
            if (is_callable($this->acquireAccessTokenLockCallback)) {
503
                call_user_func($this->acquireAccessTokenLockCallback, $this);
504
            }
505
506
            $response = $this->client()->post($this->getTokenUrl(), $body);
507
508
            Psr7\rewind_body($response);
0 ignored issues
show
Bug introduced by
The function rewind_body was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

508
            /** @scrutinizer ignore-call */ 
509
            Psr7\rewind_body($response);
Loading history...
509
            $body = json_decode($response->getBody()->getContents(), true);
510
511
            if (json_last_error() === JSON_ERROR_NONE) {
512
                $this->accessToken = $body['access_token'];
513
                $this->refreshToken = $body['refresh_token'];
514
                $this->tokenExpires = $this->getTimestampFromExpiresIn($body['expires_in']);
515
516
                if (is_callable($this->tokenUpdateCallback)) {
517
                    call_user_func($this->tokenUpdateCallback, $this);
518
                }
519
            } else {
520
                throw new ApiException('Could not acquire tokens, json decode failed. Got response: ' . $response->getBody()->getContents());
521
            }
522
        } catch (BadResponseException $ex) {
523
            throw new ApiException('Could not acquire or refresh tokens [http ' . $ex->getResponse()->getStatusCode() . ']', 0, $ex);
524
        } finally {
525
            if (is_callable($this->acquireAccessTokenUnlockCallback)) {
526
                call_user_func($this->acquireAccessTokenUnlockCallback, $this);
527
            }
528
        }
529
    }
530
531
    /**
532
     * Translates expires_in to a Unix timestamp.
533
     *
534
     * @param string $expiresIn number of seconds until the token expires
535
     *
536
     * @return int
537
     */
538
    private function getTimestampFromExpiresIn($expiresIn)
539
    {
540
        if (! ctype_digit($expiresIn)) {
541
            throw new \InvalidArgumentException('Function requires a numeric expires value');
542
        }
543
544
        return time() + $expiresIn;
545
    }
546
547
    /**
548
     * @return int the Unix timestamp at which the access token expires
549
     */
550
    public function getTokenExpires()
551
    {
552
        return $this->tokenExpires;
553
    }
554
555
    /**
556
     * @param int $tokenExpires the Unix timestamp at which the access token expires
557
     */
558
    public function setTokenExpires($tokenExpires)
559
    {
560
        $this->tokenExpires = $tokenExpires;
561
    }
562
563
    private function tokenHasExpired()
564
    {
565
        if (empty($this->tokenExpires)) {
566
            return true;
567
        }
568
569
        return $this->tokenExpires <= time() + 10;
570
    }
571
572
    private function formatUrl($endPoint, $includeDivision = true, $formatNextUrl = false)
573
    {
574
        if ($formatNextUrl) {
575
            return $endPoint;
576
        }
577
578
        if ($includeDivision) {
579
            return implode('/', [
580
                $this->getApiUrl(),
581
                $this->getCurrentDivisionNumber(),
582
                $endPoint,
583
            ]);
584
        }
585
586
        return implode('/', [
587
            $this->getApiUrl(),
588
            $endPoint,
589
        ]);
590
    }
591
592
    /**
593
     * @return mixed
594
     */
595
    public function getDivision()
596
    {
597
        return $this->division;
598
    }
599
600
    /**
601
     * @param mixed $division
602
     */
603
    public function setDivision($division)
604
    {
605
        $this->division = $division;
606
    }
607
608
    /**
609
     * @param callable $callback
610
     */
611
    public function setAcquireAccessTokenLockCallback($callback)
612
    {
613
        $this->acquireAccessTokenLockCallback = $callback;
614
    }
615
616
    /**
617
     * @param callable $callback
618
     */
619
    public function setAcquireAccessTokenUnlockCallback($callback)
620
    {
621
        $this->acquireAccessTokenUnlockCallback = $callback;
622
    }
623
624
    /**
625
     * @param callable $callback
626
     */
627
    public function setTokenUpdateCallback($callback)
628
    {
629
        $this->tokenUpdateCallback = $callback;
630
    }
631
632
    /**
633
     * Parse the reponse in the Exception to return the Exact error messages.
634
     *
635
     * @param Exception $e
636
     *
637
     * @throws ApiException
638
     */
639
    private function parseExceptionForErrorMessages(Exception $e)
640
    {
641
        if (! $e instanceof BadResponseException) {
642
            throw new ApiException($e->getMessage());
643
        }
644
645
        $response = $e->getResponse();
646
647
        $this->extractRateLimits($response);
648
649
        Psr7\rewind_body($response);
0 ignored issues
show
Bug introduced by
The function rewind_body was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

649
        /** @scrutinizer ignore-call */ 
650
        Psr7\rewind_body($response);
Loading history...
650
        $responseBody = $response->getBody()->getContents();
651
        $decodedResponseBody = json_decode($responseBody, true);
652
653
        if (! is_null($decodedResponseBody) && isset($decodedResponseBody['error']['message']['value'])) {
654
            $errorMessage = $decodedResponseBody['error']['message']['value'];
655
        } else {
656
            $errorMessage = $responseBody;
657
        }
658
659
        throw new ApiException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode());
660
    }
661
662
    /**
663
     * @return int|null The maximum number of API calls that your app is permitted to make per company, per day
664
     */
665
    public function getDailyLimit()
666
    {
667
        return $this->dailyLimit;
668
    }
669
670
    /**
671
     * @return int|null The remaining number of API calls that your app is permitted to make for a company, per day
672
     */
673
    public function getDailyLimitRemaining()
674
    {
675
        return $this->dailyLimitRemaining;
676
    }
677
678
    /**
679
     * @return int|null The time at which the rate limit window resets in UTC epoch milliseconds
680
     */
681
    public function getDailyLimitReset()
682
    {
683
        return $this->dailyLimitReset;
684
    }
685
686
    /**
687
     * @return int|null The maximum number of API calls that your app is permitted to make per company, per minute
688
     */
689
    public function getMinutelyLimit()
690
    {
691
        return $this->minutelyLimit;
692
    }
693
694
    /**
695
     * @return int|null The remaining number of API calls that your app is permitted to make for a company, per minute
696
     */
697
    public function getMinutelyLimitRemaining()
698
    {
699
        return $this->minutelyLimitRemaining;
700
    }
701
702
    /**
703
     * @return string
704
     */
705
    protected function getBaseUrl()
706
    {
707
        return $this->baseUrl;
708
    }
709
710
    /**
711
     * @return string
712
     */
713
    private function getApiUrl()
714
    {
715
        return $this->baseUrl . $this->apiUrl;
716
    }
717
718
    /**
719
     * @return string
720
     */
721
    private function getTokenUrl()
722
    {
723
        return $this->baseUrl . $this->tokenUrl;
724
    }
725
726
    /**
727
     * Set base URL for different countries according to
728
     * https://developers.exactonline.com/#Exact%20Online%20sites.html.
729
     *
730
     * @param string $baseUrl
731
     */
732
    public function setBaseUrl($baseUrl)
733
    {
734
        $this->baseUrl = $baseUrl;
735
    }
736
737
    /**
738
     * @param string $apiUrl
739
     */
740
    public function setApiUrl($apiUrl)
741
    {
742
        $this->apiUrl = $apiUrl;
743
    }
744
745
    /**
746
     * @param string $authUrl
747
     */
748
    public function setAuthUrl($authUrl)
749
    {
750
        $this->authUrl = $authUrl;
751
    }
752
753
    /**
754
     * @param string $tokenUrl
755
     */
756
    public function setTokenUrl($tokenUrl)
757
    {
758
        $this->tokenUrl = $tokenUrl;
759
    }
760
761
    private function extractRateLimits(Response $response)
762
    {
763
        $this->dailyLimit = (int) $response->getHeaderLine('X-RateLimit-Limit');
764
        $this->dailyLimitRemaining = (int) $response->getHeaderLine('X-RateLimit-Remaining');
765
        $this->dailyLimitReset = (int) $response->getHeaderLine('X-RateLimit-Reset');
766
767
        $this->minutelyLimit = (int) $response->getHeaderLine('X-RateLimit-Minutely-Limit');
768
        $this->minutelyLimitRemaining = (int) $response->getHeaderLine('X-RateLimit-Minutely-Remaining');
769
    }
770
}
771