Completed
Push — master ( d01453...1cb39d )
by Stephan
20s queued 11s
created

Connection::getDailyLimitRemaining()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
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 Response $response
382
     * @param bool     $returnSingleIfPossible
383
     *
384
     * @throws ApiException
385
     *
386
     * @return mixed
387
     */
388
    private function parseResponse(Response $response, $returnSingleIfPossible = true)
389
    {
390
        try {
391
            if ($response->getStatusCode() === 204) {
392
                return [];
393
            }
394
395
            $this->extractRateLimits($response);
396
397
            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

397
            /** @scrutinizer ignore-call */ 
398
            Psr7\rewind_body($response);
Loading history...
398
            $json = json_decode($response->getBody()->getContents(), true);
399
            if (array_key_exists('d', $json)) {
400
                if (array_key_exists('__next', $json['d'])) {
401
                    $this->nextUrl = $json['d']['__next'];
402
                } else {
403
                    $this->nextUrl = null;
404
                }
405
406
                if (array_key_exists('results', $json['d'])) {
407
                    if ($returnSingleIfPossible && count($json['d']['results']) == 1) {
408
                        return $json['d']['results'][0];
409
                    }
410
411
                    return $json['d']['results'];
412
                }
413
414
                return $json['d'];
415
            }
416
417
            return $json;
418
        } catch (\RuntimeException $e) {
419
            throw new ApiException($e->getMessage());
420
        }
421
    }
422
423
    /**
424
     * @return mixed
425
     */
426
    private function getCurrentDivisionNumber()
427
    {
428
        if (empty($this->division)) {
429
            $me = new Me($this);
430
            $this->division = $me->find()->CurrentDivision;
431
        }
432
433
        return $this->division;
434
    }
435
436
    /**
437
     * @return mixed
438
     */
439
    public function getRefreshToken()
440
    {
441
        return $this->refreshToken;
442
    }
443
444
    /**
445
     * @return mixed
446
     */
447
    public function getAccessToken()
448
    {
449
        return $this->accessToken;
450
    }
451
452
    private function acquireAccessToken()
453
    {
454
        // If refresh token not yet acquired, do token request
455
        if (empty($this->refreshToken)) {
456
            $body = [
457
                'form_params' => [
458
                    'redirect_uri'  => $this->redirectUrl,
459
                    'grant_type'    => 'authorization_code',
460
                    'client_id'     => $this->exactClientId,
461
                    'client_secret' => $this->exactClientSecret,
462
                    'code'          => $this->authorizationCode,
463
                ],
464
            ];
465
        } else { // else do refresh token request
466
            $body = [
467
                'form_params' => [
468
                    'refresh_token' => $this->refreshToken,
469
                    'grant_type'    => 'refresh_token',
470
                    'client_id'     => $this->exactClientId,
471
                    'client_secret' => $this->exactClientSecret,
472
                ],
473
            ];
474
        }
475
476
        try {
477
            if (is_callable($this->acquireAccessTokenLockCallback)) {
478
                call_user_func($this->acquireAccessTokenLockCallback, $this);
479
            }
480
481
            $response = $this->client()->post($this->getTokenUrl(), $body);
482
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
            $body = json_decode($response->getBody()->getContents(), true);
485
486
            if (json_last_error() === JSON_ERROR_NONE) {
487
                $this->accessToken = $body['access_token'];
488
                $this->refreshToken = $body['refresh_token'];
489
                $this->tokenExpires = $this->getTimestampFromExpiresIn($body['expires_in']);
490
491
                if (is_callable($this->tokenUpdateCallback)) {
492
                    call_user_func($this->tokenUpdateCallback, $this);
493
                }
494
            } else {
495
                throw new ApiException('Could not acquire tokens, json decode failed. Got response: ' . $response->getBody()->getContents());
496
            }
497
        } catch (BadResponseException $ex) {
498
            throw new ApiException('Could not acquire or refresh tokens [http ' . $ex->getResponse()->getStatusCode() . ']', 0, $ex);
499
        } finally {
500
            if (is_callable($this->acquireAccessTokenUnlockCallback)) {
501
                call_user_func($this->acquireAccessTokenUnlockCallback, $this);
502
            }
503
        }
504
    }
505
506
    /**
507
     * Translates expires_in to a Unix timestamp.
508
     *
509
     * @param string $expiresIn number of seconds until the token expires
510
     *
511
     * @return int
512
     */
513
    private function getTimestampFromExpiresIn($expiresIn)
514
    {
515
        if (! ctype_digit($expiresIn)) {
516
            throw new \InvalidArgumentException('Function requires a numeric expires value');
517
        }
518
519
        return time() + $expiresIn;
520
    }
521
522
    /**
523
     * @return int the Unix timestamp at which the access token expires
524
     */
525
    public function getTokenExpires()
526
    {
527
        return $this->tokenExpires;
528
    }
529
530
    /**
531
     * @param int $tokenExpires the Unix timestamp at which the access token expires
532
     */
533
    public function setTokenExpires($tokenExpires)
534
    {
535
        $this->tokenExpires = $tokenExpires;
536
    }
537
538
    private function tokenHasExpired()
539
    {
540
        if (empty($this->tokenExpires)) {
541
            return true;
542
        }
543
544
        return $this->tokenExpires <= time() + 10;
545
    }
546
547
    private function formatUrl($endPoint, $includeDivision = true, $formatNextUrl = false)
548
    {
549
        if ($formatNextUrl) {
550
            return $endPoint;
551
        }
552
553
        if ($includeDivision) {
554
            return implode('/', [
555
                $this->getApiUrl(),
556
                $this->getCurrentDivisionNumber(),
557
                $endPoint,
558
            ]);
559
        }
560
561
        return implode('/', [
562
            $this->getApiUrl(),
563
            $endPoint,
564
        ]);
565
    }
566
567
    /**
568
     * @return mixed
569
     */
570
    public function getDivision()
571
    {
572
        return $this->division;
573
    }
574
575
    /**
576
     * @param mixed $division
577
     */
578
    public function setDivision($division)
579
    {
580
        $this->division = $division;
581
    }
582
583
    /**
584
     * @param callable $callback
585
     */
586
    public function setAcquireAccessTokenLockCallback($callback)
587
    {
588
        $this->acquireAccessTokenLockCallback = $callback;
589
    }
590
591
    /**
592
     * @param callable $callback
593
     */
594
    public function setAcquireAccessTokenUnlockCallback($callback)
595
    {
596
        $this->acquireAccessTokenUnlockCallback = $callback;
597
    }
598
599
    /**
600
     * @param callable $callback
601
     */
602
    public function setTokenUpdateCallback($callback)
603
    {
604
        $this->tokenUpdateCallback = $callback;
605
    }
606
607
    /**
608
     * Parse the reponse in the Exception to return the Exact error messages.
609
     *
610
     * @param Exception $e
611
     *
612
     * @throws ApiException
613
     */
614
    private function parseExceptionForErrorMessages(Exception $e)
615
    {
616
        if (! $e instanceof BadResponseException) {
617
            throw new ApiException($e->getMessage());
618
        }
619
620
        $response = $e->getResponse();
621
        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

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