Passed
Pull Request — master (#423)
by
unknown
03:39 queued 01:43
created

Connection::setTokenExpires()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 3
rs 10
cc 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
    /**
157
     * Insert a custom Guzzle client.
158
     *
159
     * @param Client $client
160
     */
161
    public function setClient($client)
162
    {
163
        $this->client = $client;
164
    }
165
166
    /**
167
     * Insert a Middleware for the Guzzle Client.
168
     *
169
     * @param $middleWare
170
     */
171
    public function insertMiddleWare($middleWare)
172
    {
173
        $this->middleWares[] = $middleWare;
174
    }
175
176
    /**
177
     * @throws ApiException
178
     *
179
     * @return Client
180
     */
181
    public function connect()
182
    {
183
        // Redirect for authorization if needed (no access token or refresh token given)
184
        if ($this->needsAuthentication()) {
185
            $this->redirectForAuthorization();
186
        }
187
188
        // If access token is not set or token has expired, acquire new token
189
        if (empty($this->accessToken) || $this->tokenHasExpired()) {
190
            $this->acquireAccessToken();
191
        }
192
193
        $client = $this->client();
194
195
        return $client;
196
    }
197
198
    /**
199
     * @param string $method
200
     * @param string $endpoint
201
     * @param mixed  $body
202
     * @param array  $params
203
     * @param array  $headers
204
     *
205
     * @return Request
206
     */
207
    private function createRequest($method, $endpoint, $body = null, array $params = [], array $headers = [])
208
    {
209
        // Add default json headers to the request
210
        $headers = array_merge($headers, [
211
            'Accept'       => 'application/json',
212
            'Content-Type' => 'application/json',
213
            'Prefer'       => 'return=representation',
214
        ]);
215
216
        // If access token is not set or token has expired, acquire new token
217
        if (empty($this->accessToken) || $this->tokenHasExpired()) {
218
            $this->acquireAccessToken();
219
        }
220
221
        // If we have a token, sign the request
222
        if (! $this->needsAuthentication() && ! empty($this->accessToken)) {
223
            $headers['Authorization'] = 'Bearer ' . $this->accessToken;
224
        }
225
226
        // Create param string
227
        if (! empty($params)) {
228
            $endpoint .= '?' . http_build_query($params);
229
        }
230
231
        // Create the request
232
        $request = new Request($method, $endpoint, $headers, $body);
233
234
        return $request;
235
    }
236
237
    /**
238
     * @param string $url
239
     * @param array  $params
240
     * @param array  $headers
241
     *
242
     * @throws ApiException
243
     *
244
     * @return mixed
245
     */
246
    public function get($url, array $params = [], array $headers = [])
247
    {
248
        $url = $this->formatUrl($url, $url !== 'current/Me', $url == $this->nextUrl);
249
250
        try {
251
            $request = $this->createRequest('GET', $url, null, $params, $headers);
252
            $response = $this->client()->send($request);
253
254
            return $this->parseResponse($response, $url != $this->nextUrl);
255
        } catch (Exception $e) {
256
            $this->parseExceptionForErrorMessages($e);
257
        }
258
    }
259
260
    /**
261
     * @param string $url
262
     * @param mixed  $body
263
     *
264
     * @throws ApiException
265
     *
266
     * @return mixed
267
     */
268
    public function post($url, $body)
269
    {
270
        $url = $this->formatUrl($url);
271
272
        try {
273
            $request = $this->createRequest('POST', $url, $body);
274
            $response = $this->client()->send($request);
275
276
            return $this->parseResponse($response);
277
        } catch (Exception $e) {
278
            $this->parseExceptionForErrorMessages($e);
279
        }
280
    }
281
282
    /**
283
     * @param string $url
284
     * @param mixed  $body
285
     *
286
     * @throws ApiException
287
     *
288
     * @return mixed
289
     */
290
    public function upload($topic, $body)
291
    {
292
        $url = $this->getBaseUrl() . '/docs/XMLUpload.aspx?Topic=' . $topic . '&_Division=' . $this->getDivision();
293
294
        try {
295
            $request = $this->createRequest('POST', $url, $body);
296
            $response = $this->client()->send($request);
297
298
            return $this->parseResponseXml($response);
299
        } catch (Exception $e) {
300
            $this->parseExceptionForErrorMessages($e);
301
        }
302
    }
303
304
    /**
305
     * @param string $url
306
     * @param mixed  $body
307
     *
308
     * @throws ApiException
309
     *
310
     * @return mixed
311
     */
312
    public function put($url, $body)
313
    {
314
        $url = $this->formatUrl($url);
315
316
        try {
317
            $request = $this->createRequest('PUT', $url, $body);
318
            $response = $this->client()->send($request);
319
320
            return $this->parseResponse($response);
321
        } catch (Exception $e) {
322
            $this->parseExceptionForErrorMessages($e);
323
        }
324
    }
325
326
    /**
327
     * @param string $url
328
     *
329
     * @throws ApiException
330
     *
331
     * @return mixed
332
     */
333
    public function delete($url)
334
    {
335
        $url = $this->formatUrl($url);
336
337
        try {
338
            $request = $this->createRequest('DELETE', $url);
339
            $response = $this->client()->send($request);
340
341
            return $this->parseResponse($response);
342
        } catch (Exception $e) {
343
            $this->parseExceptionForErrorMessages($e);
344
        }
345
    }
346
347
    /**
348
     * @return string
349
     */
350
    public function getAuthUrl()
351
    {
352
        return $this->baseUrl . $this->authUrl . '?' . http_build_query([
353
            'client_id'     => $this->exactClientId,
354
            'redirect_uri'  => $this->redirectUrl,
355
            'response_type' => 'code',
356
        ]);
357
    }
358
359
    /**
360
     * @param mixed $exactClientId
361
     */
362
    public function setExactClientId($exactClientId)
363
    {
364
        $this->exactClientId = $exactClientId;
365
    }
366
367
    /**
368
     * @param mixed $exactClientSecret
369
     */
370
    public function setExactClientSecret($exactClientSecret)
371
    {
372
        $this->exactClientSecret = $exactClientSecret;
373
    }
374
375
    /**
376
     * @param mixed $authorizationCode
377
     */
378
    public function setAuthorizationCode($authorizationCode)
379
    {
380
        $this->authorizationCode = $authorizationCode;
381
    }
382
383
    /**
384
     * @param mixed $accessToken
385
     */
386
    public function setAccessToken($accessToken)
387
    {
388
        $this->accessToken = $accessToken;
389
    }
390
391
    /**
392
     * @param mixed $refreshToken
393
     */
394
    public function setRefreshToken($refreshToken)
395
    {
396
        $this->refreshToken = $refreshToken;
397
    }
398
399
    public function redirectForAuthorization()
400
    {
401
        $authUrl = $this->getAuthUrl();
402
        header('Location: ' . $authUrl);
403
        exit;
404
    }
405
406
    /**
407
     * @param mixed $redirectUrl
408
     */
409
    public function setRedirectUrl($redirectUrl)
410
    {
411
        $this->redirectUrl = $redirectUrl;
412
    }
413
414
    /**
415
     * @return bool
416
     */
417
    public function needsAuthentication()
418
    {
419
        return empty($this->refreshToken) && empty($this->authorizationCode);
420
    }
421
422
    /**
423
     * @param Response $response
424
     * @param bool     $returnSingleIfPossible
425
     *
426
     * @throws ApiException
427
     *
428
     * @return mixed
429
     */
430
    private function parseResponse(Response $response, $returnSingleIfPossible = true)
431
    {
432
        try {
433
            if ($response->getStatusCode() === 204) {
434
                return [];
435
            }
436
437
            $this->extractRateLimits($response);
438
439
            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

439
            /** @scrutinizer ignore-call */ 
440
            Psr7\rewind_body($response);
Loading history...
440
            $json = json_decode($response->getBody()->getContents(), true);
441
            if (false === is_array($json)) {
442
                throw new ApiException('Json decode failed. Got response: ' . $response->getBody()->getContents());
443
            }
444
            if (array_key_exists('d', $json)) {
445
                if (array_key_exists('__next', $json['d'])) {
446
                    $this->nextUrl = $json['d']['__next'];
447
                } else {
448
                    $this->nextUrl = null;
449
                }
450
451
                if (array_key_exists('results', $json['d'])) {
452
                    if ($returnSingleIfPossible && count($json['d']['results']) == 1) {
453
                        return $json['d']['results'][0];
454
                    }
455
456
                    return $json['d']['results'];
457
                }
458
459
                return $json['d'];
460
            }
461
462
            return $json;
463
        } catch (\RuntimeException $e) {
464
            throw new ApiException($e->getMessage());
465
        }
466
    }
467
468
    /**
469
     * @param Response $response
470
     *
471
     * @throws ApiException
472
     *
473
     * @return mixed
474
     */
475
    private function parseResponseXml(Response $response)
476
    {
477
        try {
478
            if ($response->getStatusCode() === 204) {
479
                return [];
480
            }
481
482
            $answer = [];
483
            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

483
            /** @scrutinizer ignore-call */ 
484
            Psr7\rewind_body($response);
Loading history...
484
            $simpleXml = new \SimpleXMLElement($response->getBody()->getContents());
485
486
            foreach ($simpleXml->Messages as $message) {
487
                $keyAlt = (string) $message->Message->Topic->Data->attributes()['keyAlt'];
488
                $answer[$keyAlt] = (string) $message->Message->Description;
489
            }
490
491
            return $answer;
492
        } catch (\RuntimeException $e) {
493
            throw new ApiException($e->getMessage());
494
        }
495
    }
496
497
    /**
498
     * @return mixed
499
     */
500
    private function getCurrentDivisionNumber()
501
    {
502
        if (empty($this->division)) {
503
            $me = new Me($this);
504
            $this->division = $me->find()->CurrentDivision;
505
        }
506
507
        return $this->division;
508
    }
509
510
    /**
511
     * @return mixed
512
     */
513
    public function getRefreshToken()
514
    {
515
        return $this->refreshToken;
516
    }
517
518
    /**
519
     * @return mixed
520
     */
521
    public function getAccessToken()
522
    {
523
        return $this->accessToken;
524
    }
525
526
    private function acquireAccessToken()
527
    {
528
        try {
529
            if (is_callable($this->acquireAccessTokenLockCallback)) {
530
                call_user_func($this->acquireAccessTokenLockCallback, $this);
531
            }
532
533
            // If refresh token not yet acquired, do token request
534
            if (empty($this->refreshToken)) {
535
                $body = [
536
                    'form_params' => [
537
                        'redirect_uri'  => $this->redirectUrl,
538
                        'grant_type'    => 'authorization_code',
539
                        'client_id'     => $this->exactClientId,
540
                        'client_secret' => $this->exactClientSecret,
541
                        'code'          => $this->authorizationCode,
542
                    ],
543
                ];
544
            } else { // else do refresh token request
545
                $body = [
546
                    'form_params' => [
547
                        'refresh_token' => $this->refreshToken,
548
                        'grant_type'    => 'refresh_token',
549
                        'client_id'     => $this->exactClientId,
550
                        'client_secret' => $this->exactClientSecret,
551
                    ],
552
                ];
553
            }
554
555
            $response = $this->client()->post($this->getTokenUrl(), $body);
556
557
            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

557
            /** @scrutinizer ignore-call */ 
558
            Psr7\rewind_body($response);
Loading history...
558
            $body = json_decode($response->getBody()->getContents(), true);
559
560
            if (json_last_error() === JSON_ERROR_NONE) {
561
                $this->accessToken = $body['access_token'];
562
                $this->refreshToken = $body['refresh_token'];
563
                $this->tokenExpires = $this->getTimestampFromExpiresIn($body['expires_in']);
564
565
                if (is_callable($this->tokenUpdateCallback)) {
566
                    call_user_func($this->tokenUpdateCallback, $this);
567
                }
568
            } else {
569
                throw new ApiException('Could not acquire tokens, json decode failed. Got response: ' . $response->getBody()->getContents());
570
            }
571
        } catch (BadResponseException $ex) {
572
            throw new ApiException('Could not acquire or refresh tokens [http ' . $ex->getResponse()->getStatusCode() . ']', 0, $ex);
573
        } finally {
574
            if (is_callable($this->acquireAccessTokenUnlockCallback)) {
575
                call_user_func($this->acquireAccessTokenUnlockCallback, $this);
576
            }
577
        }
578
    }
579
580
    /**
581
     * Translates expires_in to a Unix timestamp.
582
     *
583
     * @param string $expiresIn number of seconds until the token expires
584
     *
585
     * @return int
586
     */
587
    private function getTimestampFromExpiresIn($expiresIn)
588
    {
589
        if (! ctype_digit($expiresIn)) {
590
            throw new \InvalidArgumentException('Function requires a numeric expires value');
591
        }
592
593
        return time() + $expiresIn;
594
    }
595
596
    /**
597
     * @return int the Unix timestamp at which the access token expires
598
     */
599
    public function getTokenExpires()
600
    {
601
        return $this->tokenExpires;
602
    }
603
604
    /**
605
     * @param int $tokenExpires the Unix timestamp at which the access token expires
606
     */
607
    public function setTokenExpires($tokenExpires)
608
    {
609
        $this->tokenExpires = $tokenExpires;
610
    }
611
612
    private function tokenHasExpired()
613
    {
614
        if (empty($this->tokenExpires)) {
615
            return true;
616
        }
617
618
        return ($this->tokenExpires - 60) < time();
619
    }
620
621
    private function formatUrl($endPoint, $includeDivision = true, $formatNextUrl = false)
622
    {
623
        if ($formatNextUrl) {
624
            return $endPoint;
625
        }
626
627
        if ($includeDivision) {
628
            return implode('/', [
629
                $this->getApiUrl(),
630
                $this->getCurrentDivisionNumber(),
631
                $endPoint,
632
            ]);
633
        }
634
635
        return implode('/', [
636
            $this->getApiUrl(),
637
            $endPoint,
638
        ]);
639
    }
640
641
    /**
642
     * @return mixed
643
     */
644
    public function getDivision()
645
    {
646
        return $this->division;
647
    }
648
649
    /**
650
     * @param mixed $division
651
     */
652
    public function setDivision($division)
653
    {
654
        $this->division = $division;
655
    }
656
657
    /**
658
     * @param callable $callback
659
     */
660
    public function setAcquireAccessTokenLockCallback($callback)
661
    {
662
        $this->acquireAccessTokenLockCallback = $callback;
663
    }
664
665
    /**
666
     * @param callable $callback
667
     */
668
    public function setAcquireAccessTokenUnlockCallback($callback)
669
    {
670
        $this->acquireAccessTokenUnlockCallback = $callback;
671
    }
672
673
    /**
674
     * @param callable $callback
675
     */
676
    public function setTokenUpdateCallback($callback)
677
    {
678
        $this->tokenUpdateCallback = $callback;
679
    }
680
681
    /**
682
     * Parse the reponse in the Exception to return the Exact error messages.
683
     *
684
     * @param Exception $e
685
     *
686
     * @throws ApiException
687
     */
688
    private function parseExceptionForErrorMessages(Exception $e)
689
    {
690
        if (! $e instanceof BadResponseException) {
691
            throw new ApiException($e->getMessage(), 0, $e);
692
        }
693
694
        $response = $e->getResponse();
695
696
        $this->extractRateLimits($response);
0 ignored issues
show
Bug introduced by
It seems like $response can also be of type null; however, parameter $response of Picqer\Financials\Exact\...on::extractRateLimits() does only seem to accept GuzzleHttp\Psr7\Response, maybe add an additional type check? ( Ignorable by Annotation )

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

696
        $this->extractRateLimits(/** @scrutinizer ignore-type */ $response);
Loading history...
697
698
        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

698
        /** @scrutinizer ignore-call */ 
699
        Psr7\rewind_body($response);
Loading history...
699
        $responseBody = $response->getBody()->getContents();
700
        $decodedResponseBody = json_decode($responseBody, true);
701
702
        if (! is_null($decodedResponseBody) && isset($decodedResponseBody['error']['message']['value'])) {
703
            $errorMessage = $decodedResponseBody['error']['message']['value'];
704
        } else {
705
            $errorMessage = $responseBody;
706
        }
707
708
        throw new ApiException('Error ' . $response->getStatusCode() . ': ' . $errorMessage, $response->getStatusCode(), $e);
709
    }
710
711
    /**
712
     * @return int|null The maximum number of API calls that your app is permitted to make per company, per day
713
     */
714
    public function getDailyLimit()
715
    {
716
        return $this->dailyLimit;
717
    }
718
719
    /**
720
     * @return int|null The remaining number of API calls that your app is permitted to make for a company, per day
721
     */
722
    public function getDailyLimitRemaining()
723
    {
724
        return $this->dailyLimitRemaining;
725
    }
726
727
    /**
728
     * @return int|null The time at which the rate limit window resets in UTC epoch milliseconds
729
     */
730
    public function getDailyLimitReset()
731
    {
732
        return $this->dailyLimitReset;
733
    }
734
735
    /**
736
     * @return int|null The maximum number of API calls that your app is permitted to make per company, per minute
737
     */
738
    public function getMinutelyLimit()
739
    {
740
        return $this->minutelyLimit;
741
    }
742
743
    /**
744
     * @return int|null The remaining number of API calls that your app is permitted to make for a company, per minute
745
     */
746
    public function getMinutelyLimitRemaining()
747
    {
748
        return $this->minutelyLimitRemaining;
749
    }
750
751
    /**
752
     * @return string
753
     */
754
    protected function getBaseUrl()
755
    {
756
        return $this->baseUrl;
757
    }
758
759
    /**
760
     * @return string
761
     */
762
    private function getApiUrl()
763
    {
764
        return $this->baseUrl . $this->apiUrl;
765
    }
766
767
    /**
768
     * @return string
769
     */
770
    private function getTokenUrl()
771
    {
772
        return $this->baseUrl . $this->tokenUrl;
773
    }
774
775
    /**
776
     * Set base URL for different countries according to
777
     * https://developers.exactonline.com/#Exact%20Online%20sites.html.
778
     *
779
     * @param string $baseUrl
780
     */
781
    public function setBaseUrl($baseUrl)
782
    {
783
        $this->baseUrl = $baseUrl;
784
    }
785
786
    /**
787
     * @param string $apiUrl
788
     */
789
    public function setApiUrl($apiUrl)
790
    {
791
        $this->apiUrl = $apiUrl;
792
    }
793
794
    /**
795
     * @param string $authUrl
796
     */
797
    public function setAuthUrl($authUrl)
798
    {
799
        $this->authUrl = $authUrl;
800
    }
801
802
    /**
803
     * @param string $tokenUrl
804
     */
805
    public function setTokenUrl($tokenUrl)
806
    {
807
        $this->tokenUrl = $tokenUrl;
808
    }
809
810
    private function extractRateLimits(Response $response)
811
    {
812
        $this->dailyLimit = (int) $response->getHeaderLine('X-RateLimit-Limit');
813
        $this->dailyLimitRemaining = (int) $response->getHeaderLine('X-RateLimit-Remaining');
814
        $this->dailyLimitReset = (int) $response->getHeaderLine('X-RateLimit-Reset');
815
816
        $this->minutelyLimit = (int) $response->getHeaderLine('X-RateLimit-Minutely-Limit');
817
        $this->minutelyLimitRemaining = (int) $response->getHeaderLine('X-RateLimit-Minutely-Remaining');
818
    }
819
}
820