Passed
Pull Request — master (#27)
by Edoardo
04:25 queued 02:27
created

BEditaClient   F

Complexity

Total Complexity 62

Size/Duplication

Total Lines 668
Duplicated Lines 0 %

Importance

Changes 21
Bugs 6 Features 1
Metric Value
eloc 143
c 21
b 6
f 1
dl 0
loc 668
rs 3.44
wmc 62

34 Methods

Rating   Name   Duplication   Size   Complexity  
A getDefaultHeaders() 0 3 1
A getStatusCode() 0 3 2
A getTokens() 0 3 1
A getObjects() 0 3 1
A getStatusMessage() 0 3 2
A getApiBaseUrl() 0 3 1
A getObject() 0 3 1
A getResponse() 0 3 1
A __construct() 0 11 1
A authenticate() 0 5 1
A refreshTokens() 0 17 3
A removeRelated() 0 5 1
A get() 0 5 1
A getRelated() 0 3 1
A setupTokens() 0 7 2
A addRelated() 0 5 1
A getResponseBody() 0 12 3
A deleteObject() 0 3 1
A replaceRelated() 0 3 1
A sendRequest() 0 25 4
A upload() 0 14 4
A saveObject() 0 3 1
A sendRequestRetry() 0 17 5
A thumbs() 0 11 4
A save() 0 20 3
A post() 0 5 1
A patch() 0 5 1
A restoreObject() 0 10 1
A createMediaFromStream() 0 15 3
A delete() 0 5 1
A remove() 0 3 1
A schema() 0 5 1
A relationData() 0 7 1
A requestUri() 0 18 5

How to fix   Complexity   

Complex Class

Complex classes like BEditaClient 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 BEditaClient, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * BEdita, API-first content management framework
4
 * Copyright 2018 ChannelWeb Srl, Chialab Srl
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 */
10
11
namespace BEdita\SDK;
12
13
use GuzzleHttp\Psr7\Request;
14
use GuzzleHttp\Psr7\Uri;
15
use Http\Adapter\Guzzle6\Client;
16
use Psr\Http\Message\ResponseInterface;
17
use WoohooLabs\Yang\JsonApi\Client\JsonApiClient;
18
19
/**
20
 * BEdita4 API Client class
21
 */
22
class BEditaClient
23
{
24
    use LogTrait;
25
26
    /**
27
     * Last response.
28
     *
29
     * @var \Psr\Http\Message\ResponseInterface
30
     */
31
    private $response = null;
32
33
    /**
34
     * BEdita4 API base URL
35
     *
36
     * @var string
37
     */
38
    private $apiBaseUrl = null;
39
40
    /**
41
     * BEdita4 API KEY
42
     *
43
     * @var string
44
     */
45
    private $apiKey = null;
46
47
    /**
48
     * Default headers in request
49
     *
50
     * @var array
51
     */
52
    private $defaultHeaders = [
53
        'Accept' => 'application/vnd.api+json',
54
    ];
55
56
    /**
57
     * Default headers in request
58
     *
59
     * @var array
60
     */
61
    private $defaultContentTypeHeader = [
62
        'Content-Type' => 'application/json',
63
    ];
64
65
    /**
66
     * JWT Auth tokens
67
     *
68
     * @var array
69
     */
70
    private $tokens = [];
71
72
    /**
73
     * JSON API BEdita4 client
74
     *
75
     * @var \WoohooLabs\Yang\JsonApi\Client\JsonApiClient
76
     */
77
    private $jsonApiClient = null;
78
79
    /**
80
     * Setup main client options:
81
     *  - API base URL
82
     *  - API KEY
83
     *  - Auth tokens 'jwt' and 'renew' (optional)
84
     *
85
     * @param string $apiUrl API base URL
86
     * @param string $apiKey API key
87
     * @param array $tokens JWT Autorization tokens as associative array ['jwt' => '###', 'renew' => '###']
88
     * @return void
89
     */
90
    public function __construct(string $apiUrl, ?string $apiKey = null, array $tokens = [])
91
    {
92
        $this->apiBaseUrl = $apiUrl;
93
        $this->apiKey = $apiKey;
94
95
        $this->defaultHeaders['X-Api-Key'] = $this->apiKey;
96
        $this->setupTokens($tokens);
97
98
        // setup an asynchronous JSON API client
99
        $guzzleClient = Client::createWithConfig([]);
100
        $this->jsonApiClient = new JsonApiClient($guzzleClient);
101
    }
102
103
    /**
104
     * Setup JWT access and refresh tokens.
105
     *
106
     * @param array $tokens JWT tokens as associative array ['jwt' => '###', 'renew' => '###']
107
     * @return void
108
     */
109
    public function setupTokens(array $tokens): void
110
    {
111
        $this->tokens = $tokens;
112
        if (!empty($tokens['jwt'])) {
113
            $this->defaultHeaders['Authorization'] = sprintf('Bearer %s', $tokens['jwt']);
114
        } else {
115
            unset($this->defaultHeaders['Authorization']);
116
        }
117
    }
118
119
    /**
120
     * Get default headers in use on every request
121
     *
122
     * @return array Default headers
123
     * @codeCoverageIgnore
124
     */
125
    public function getDefaultHeaders(): array
126
    {
127
        return $this->defaultHeaders;
128
    }
129
130
    /**
131
     * Get API base URL used tokens
132
     *
133
     * @return string API base URL
134
     * @codeCoverageIgnore
135
     */
136
    public function getApiBaseUrl(): string
137
    {
138
        return $this->apiBaseUrl;
139
    }
140
141
    /**
142
     * Get current used tokens
143
     *
144
     * @return array Current tokens
145
     * @codeCoverageIgnore
146
     */
147
    public function getTokens(): array
148
    {
149
        return $this->tokens;
150
    }
151
152
    /**
153
     * Get last HTTP response
154
     *
155
     * @return ResponseInterface|null Response PSR interface
156
     * @codeCoverageIgnore
157
     */
158
    public function getResponse(): ?ResponseInterface
159
    {
160
        return $this->response;
161
    }
162
163
    /**
164
     * Get HTTP response status code
165
     * Return null if no response is available
166
     *
167
     * @return int|null Status code.
168
     */
169
    public function getStatusCode(): ?int
170
    {
171
        return $this->response ? $this->response->getStatusCode() : null;
172
    }
173
174
    /**
175
     * Get HTTP response status message
176
     * Return null if no response is available
177
     *
178
     * @return string|null Message related to status code.
179
     */
180
    public function getStatusMessage(): ?string
181
    {
182
        return $this->response ? $this->response->getReasonPhrase() : null;
183
    }
184
185
    /**
186
     * Get response body serialized into a PHP array
187
     *
188
     * @return array|null Response body as PHP array.
189
     */
190
    public function getResponseBody(): ?array
191
    {
192
        $response = $this->getResponse();
193
        if (empty($response)) {
194
            return null;
195
        }
196
        $responseBody = json_decode((string)$response->getBody(), true);
197
        if (!is_array($responseBody)) {
198
            return null;
199
        }
200
201
        return $responseBody;
202
    }
203
204
    /**
205
     * Classic authentication via POST /auth using username and password
206
     *
207
     * @param string $username username
208
     * @param string $password password
209
     * @return array|null Response in array format
210
     */
211
    public function authenticate(string $username, string $password): ?array
212
    {
213
        $body = json_encode(compact('username', 'password'));
214
215
        return $this->post('/auth', $body, ['Content-Type' => 'application/json']);
216
    }
217
218
    /**
219
     * Send a GET request a list of resources or objects or a single resource or object
220
     *
221
     * @param string $path Endpoint URL path to invoke
222
     * @param array|null $query Optional query string
223
     * @param array|null $headers Headers
224
     * @return array|null Response in array format
225
     */
226
    public function get(string $path, ?array $query = null, ?array $headers = null): ?array
227
    {
228
        $this->sendRequestRetry('GET', $path, $query, $headers);
229
230
        return $this->getResponseBody();
231
    }
232
233
    /**
234
     * GET a list of resources or objects of a given type
235
     *
236
     * @param string $type Object type name
237
     * @param array|null $query Optional query string
238
     * @param array|null $headers Custom request headers
239
     * @return array|null Response in array format
240
     */
241
    public function getObjects(string $type = 'objects', ?array $query = null, ?array $headers = null): ?array
242
    {
243
        return $this->get(sprintf('/%s', $type), $query, $headers);
244
    }
245
246
    /**
247
     * GET a single object of a given type
248
     *
249
     * @param int|string $id Object id
250
     * @param string $type Object type name
251
     * @param array|null $query Optional query string
252
     * @param array|null $headers Custom request headers
253
     * @return array|null Response in array format
254
     */
255
    public function getObject($id, string $type = 'objects', ?array $query = null, ?array $headers = null): ?array
256
    {
257
        return $this->get(sprintf('/%s/%s', $type, $id), $query, $headers);
258
    }
259
260
    /**
261
     * Get a list of related resources or objects
262
     *
263
     * @param int|string $id Resource id or object uname/id
264
     * @param string $type Type name
265
     * @param string $relation Relation name
266
     * @param array|null $query Optional query string
267
     * @param array|null $headers Custom request headers
268
     * @return array|null Response in array format
269
     */
270
    public function getRelated($id, string $type, string $relation, ?array $query = null, ?array $headers = null): ?array
271
    {
272
        return $this->get(sprintf('/%s/%s/%s', $type, $id, $relation), $query, $headers);
273
    }
274
275
    /**
276
     * Add a list of related resources or objects
277
     *
278
     * @param int|string $id Resource id or object uname/id
279
     * @param string $type Type name
280
     * @param string $relation Relation name
281
     * @param array $data Related resources or objects to add, MUST contain id and type
282
     * @param array|null $headers Custom request headers
283
     * @return array|null Response in array format
284
     */
285
    public function addRelated($id, string $type, string $relation, array $data, ?array $headers = null): ?array
286
    {
287
        $body = compact('data');
288
289
        return $this->post(sprintf('/%s/%s/relationships/%s', $type, $id, $relation), json_encode($body), $headers);
290
    }
291
292
    /**
293
     * Remove a list of related resources or objects
294
     *
295
     * @param int|string $id Resource id or object uname/id
296
     * @param string $type Type name
297
     * @param string $relation Relation name
298
     * @param array $data Related resources or objects to remove from relation
299
     * @param array|null $headers Custom request headers
300
     * @return array|null Response in array format
301
     */
302
    public function removeRelated($id, string $type, string $relation, array $data, ?array $headers = null): ?array
303
    {
304
        $body = compact('data');
305
306
        return $this->delete(sprintf('/%s/%s/relationships/%s', $type, $id, $relation), json_encode($body), $headers);
307
    }
308
309
    /**
310
     * Replace a list of related resources or objects: previuosly related are removed and replaced with these.
311
     *
312
     * @param int|string $id Object id
313
     * @param string $type Object type name
314
     * @param string $relation Relation name
315
     * @param array $data Related resources or objects to insert
316
     * @param array|null $headers Custom request headers
317
     * @return array|null Response in array format
318
     */
319
    public function replaceRelated($id, string $type, string $relation, array $data, ?array $headers = null): ?array
0 ignored issues
show
Unused Code introduced by
The parameter $data is not used and could be removed. ( Ignorable by Annotation )

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

319
    public function replaceRelated($id, string $type, string $relation, /** @scrutinizer ignore-unused */ array $data, ?array $headers = null): ?array

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
320
    {
321
        return $this->patch(sprintf('/%s/%s/relationships/%s', $type, $id, $relation), json_encode(['data' => $items]), $headers);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $items seems to be never defined.
Loading history...
322
    }
323
324
    /**
325
     * Create a new object or resource (POST) or modify an existing one (PATCH)
326
     *
327
     * @param string $type Object or resource type name
328
     * @param array $data Object or resource data to save
329
     * @param array|null $headers Custom request headers
330
     * @return array|null Response in array format
331
     */
332
    public function save(string $type, array $data, ?array $headers = null): ?array
333
    {
334
        $id = null;
335
        if (array_key_exists('id', $data)) {
336
            $id = $data['id'];
337
            unset($data['id']);
338
        }
339
340
        $body = [
341
            'data' => [
342
                'type' => $type,
343
                'attributes' => $data,
344
            ],
345
        ];
346
        if (!$id) {
347
            return $this->post(sprintf('/%s', $type), json_encode($body), $headers);
348
        }
349
        $body['data']['id'] = $id;
350
351
        return $this->patch(sprintf('/%s/%s', $type, $id), json_encode($body), $headers);
352
    }
353
354
    /**
355
     * [DEPRECATED] Create a new object (POST) or modify an existing one (PATCH)
356
     *
357
     * @param string $type Object type name
358
     * @param array $data Object data to save
359
     * @param array|null $headers Custom request headers
360
     * @return array|null Response in array format
361
     * @deprecated Use `save()` method instead
362
     * @codeCoverageIgnore
363
     */
364
    public function saveObject(string $type, array $data, ?array $headers = null): ?array
365
    {
366
        return $this->save($type, $data, $headers);
367
    }
368
369
    /**
370
     * Delete an object (DELETE) => move to trashcan.
371
     *
372
     * @param int|string $id Object id
373
     * @param string $type Object type name
374
     * @return array|null Response in array format
375
     */
376
    public function deleteObject($id, string $type): ?array
377
    {
378
        return $this->delete(sprintf('/%s/%s', $type, $id));
379
    }
380
381
    /**
382
     * Remove an object => permanently remove object from trashcan.
383
     *
384
     * @param int|string $id Object id
385
     * @return array|null Response in array format
386
     */
387
    public function remove($id): ?array
388
    {
389
        return $this->delete(sprintf('/trash/%s', $id));
390
    }
391
392
    /**
393
     * Upload file (POST)
394
     *
395
     * @param string $filename The file name
396
     * @param string $filepath File full path: could be on a local filesystem or a remote reachable URL
397
     * @param array|null $headers Custom request headers
398
     * @return array|null Response in array format
399
     * @throws BEditaClientException
400
     */
401
    public function upload(string $filename, string $filepath, ?array $headers = null): ?array
402
    {
403
        if (!file_exists($filepath)) {
404
            throw new BEditaClientException('File not found', 500);
405
        }
406
        $file = file_get_contents($filepath);
407
        if (!$file) {
408
            throw new BEditaClientException('File get contents failed', 500);
409
        }
410
        if (empty($headers['Content-Type'])) {
411
            $headers['Content-Type'] = mime_content_type($filepath);
412
        }
413
414
        return $this->post(sprintf('/streams/upload/%s', $filename), $file, $headers);
415
    }
416
417
    /**
418
     * Create media by type and body data and link it to a stream:
419
     *  - `POST /:type` with `$body` as payload, create media object
420
     *  - `PATCH /streams/:stream_id/relationships/object` modify stream adding relation to media
421
     *  - `GET /:type/:id` get media data
422
     *
423
     * @param string $streamId The stream identifier
424
     * @param string $type The type
425
     * @param array $body The body data
426
     * @return array|null Response in array format
427
     * @throws BEditaClientException
428
     */
429
    public function createMediaFromStream($streamId, string $type, array $body): ?array
430
    {
431
        $response = $this->post(sprintf('/%s', $type), json_encode($body));
432
        if (empty($response)) {
433
            throw new BEditaClientException('Invalid response from POST ' . sprintf('/%s', $type));
434
        }
435
        $id = $response['data']['id'];
436
        $data = compact('id', 'type');
437
        $body = compact('data');
438
        $response = $this->patch(sprintf('/streams/%s/relationships/object', $streamId), json_encode($body));
439
        if (empty($response)) {
440
            throw new BEditaClientException('Invalid response from PATCH ' . sprintf('/streams/%s/relationships/object', $id));
441
        }
442
443
        return $this->getObject($data['id'], $data['type']);
444
    }
445
446
    /**
447
     * Thumbnail request using `GET /media/thumbs` endpoint
448
     *
449
     *  Usage:
450
     *          thumbs(123) => `GET /media/thumbs/123`
451
     *          thumbs(123, ['preset' => 'glide']) => `GET /media/thumbs/123&preset=glide`
452
     *          thumbs(null, ['ids' => '123,124,125']) => `GET /media/thumbs?ids=123,124,125`
453
     *          thumbs(null, ['ids' => '123,124,125', 'preset' => 'async']) => `GET /media/thumbs?ids=123,124,125&preset=async`
454
     *          thumbs(123, ['options' => ['w' => 100, 'h' => 80, 'fm' => 'jpg']]) => `GET /media/thumbs/123/options[w]=100&options[h]=80&options[fm]=jpg` (these options could be not available... just set in preset(s))
455
     *
456
     * @param int|null $id the media Id.
457
     * @param array $query The query params for thumbs call.
458
     * @return array|null Response in array format
459
     */
460
    public function thumbs($id = null, $query = []): ?array
461
    {
462
        if (empty($id) && empty($query['ids'])) {
463
            throw new BEditaClientException('Invalid empty id|ids for thumbs');
464
        }
465
        $endpoint = '/media/thumbs';
466
        if (!empty($id)) {
467
            $endpoint .= sprintf('/%d', $id);
468
        }
469
470
        return $this->get($endpoint, $query);
471
    }
472
473
    /**
474
     * Get JSON SCHEMA of a resource or object
475
     *
476
     * @param string $type Object or resource type name
477
     * @return array|null JSON SCHEMA in array format
478
     */
479
    public function schema(string $type): ?array
480
    {
481
        $h = ['Accept' => 'application/schema+json'];
482
483
        return $this->get(sprintf('/model/schema/%s', $type), null, $h);
484
    }
485
486
    /**
487
     * Get info of a relation (data, params) and get left/right object types
488
     *
489
     * @param string $name relation name
490
     * @return array|null relation data in array format
491
     */
492
    public function relationData(string $name): ?array
493
    {
494
        $query = [
495
            'include' => 'left_object_types,right_object_types',
496
        ];
497
498
        return $this->get(sprintf('/model/relations/%s', $name), $query);
499
    }
500
501
    /**
502
     * Restore object from trash
503
     *
504
     * @param int|string $id Object id
505
     * @param string $type Object type name
506
     * @return array|null Response in array format
507
     */
508
    public function restoreObject($id, string $type): ?array
509
    {
510
        $body = [
511
            'data' => [
512
                'id' => $id,
513
                'type' => $type,
514
            ],
515
        ];
516
517
        return $this->patch(sprintf('/%s/%s', 'trash', $id), json_encode($body));
518
    }
519
520
    /**
521
     * Send a PATCH request to modify a single resource or object
522
     *
523
     * @param string $path Endpoint URL path to invoke
524
     * @param mixed $body Request body
525
     * @param array|null $headers Custom request headers
526
     * @return array|null Response in array format
527
     */
528
    public function patch(string $path, $body, ?array $headers = null): ?array
529
    {
530
        $this->sendRequestRetry('PATCH', $path, null, $headers, $body);
531
532
        return $this->getResponseBody();
533
    }
534
535
    /**
536
     * Send a POST request for creating resources or objects or other operations like /auth
537
     *
538
     * @param string $path Endpoint URL path to invoke
539
     * @param mixed $body Request body
540
     * @param array|null $headers Custom request headers
541
     * @return array|null Response in array format
542
     */
543
    public function post(string $path, $body, ?array $headers = null): ?array
544
    {
545
        $this->sendRequestRetry('POST', $path, null, $headers, $body);
546
547
        return $this->getResponseBody();
548
    }
549
550
    /**
551
     * Send a DELETE request
552
     *
553
     * @param string $path Endpoint URL path to invoke.
554
     * @param mixed $body Request body
555
     * @param array|null $headers Custom request headers
556
     * @return array|null Response in array format.
557
     */
558
    public function delete(string $path, $body = null, ?array $headers = null): ?array
559
    {
560
        $this->sendRequestRetry('DELETE', $path, null, $headers, $body);
561
562
        return $this->getResponseBody();
563
    }
564
565
    /**
566
     * Send a generic JSON API request with a basic retry policy on expired token exception.
567
     *
568
     * @param string $method HTTP Method.
569
     * @param string $path Endpoint URL path.
570
     * @param array|null $query Query string parameters.
571
     * @param string[]|null $headers Custom request headers.
572
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
573
     * @return \Psr\Http\Message\ResponseInterface
574
     */
575
    protected function sendRequestRetry(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface
576
    {
577
        try {
578
            return $this->sendRequest($method, $path, $query, $headers, $body);
579
        } catch (BEditaClientException $e) {
580
            // Handle error.
581
            $attributes = $e->getAttributes();
582
            if ($e->getCode() !== 401 || empty($attributes['code']) || $attributes['code'] !== 'be_token_expired') {
583
                // Not an expired token's fault.
584
                throw $e;
585
            }
586
587
            // Refresh and retry.
588
            $this->refreshTokens();
589
            unset($headers['Authorization']);
590
591
            return $this->sendRequest($method, $path, $query, $headers, $body);
592
        }
593
    }
594
595
    /**
596
     * Send a generic JSON API request and retrieve response $this->response
597
     *
598
     * @param string $method HTTP Method.
599
     * @param string $path Endpoint URL path (with or without starting `/`) or absolute API path
600
     * @param array|null $query Query string parameters.
601
     * @param string[]|null $headers Custom request headers.
602
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
603
     * @return \Psr\Http\Message\ResponseInterface
604
     * @throws BEditaClientException Throws an exception if server response code is not 20x.
605
     */
606
    protected function sendRequest(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface
607
    {
608
        $uri = $this->requestUri($path, $query);
609
        $headers = array_merge($this->defaultHeaders, (array)$headers);
610
611
        // set default `Content-Type` if not set and $body not empty
612
        if (!empty($body)) {
613
            $headers = array_merge($this->defaultContentTypeHeader, $headers);
614
        }
615
616
        // Send the request synchronously to retrieve the response.
617
        // Request and response log performed only if configured via `initLogger()`
618
        $request = new Request($method, $uri, $headers, $body);
619
        $this->logRequest($request);
620
        $this->response = $this->jsonApiClient->sendRequest($request);
621
        $this->logResponse($this->response);
622
        if ($this->getStatusCode() >= 400) {
623
            // Something bad just happened.
624
            $response = $this->getResponseBody();
625
            // Message will be 'error` array, if absent use status massage
626
            $message = empty($response['error']) ? $this->getStatusMessage() : $response['error'];
627
            throw new BEditaClientException($message, $this->getStatusCode());
628
        }
629
630
        return $this->response;
631
    }
632
633
    /**
634
     * Create request URI from path.
635
     * If path is absolute, i.e. it starts with 'http://' or 'https://', path is unchanged.
636
     * Otherwise `$this->apiBaseUrl` is prefixed, prepending a `/` if necessary.
637
     *
638
     * @param string $path Endpoint URL path (with or without starting `/`) or absolute API path
639
     * @param array|null $query Query string parameters.
640
     * @return Uri
641
     */
642
    protected function requestUri(string $path, ?array $query = null): Uri
643
    {
644
        if (strpos($path, 'https://') !== 0 && strpos($path, 'http://') !== 0) {
645
            if (substr($path, 0, 1) !== '/') {
646
                $path = '/' . $path;
647
            }
648
            $path = $this->apiBaseUrl . $path;
649
        }
650
        $uri = new Uri($path);
651
652
        // if path contains query strings, remove them from path and add them to query filter
653
        parse_str($uri->getQuery(), $uriQuery);
654
        if ($query) {
655
            $query = array_merge((array)$uriQuery, (array)$query);
656
            $uri = $uri->withQuery(http_build_query($query));
657
        }
658
659
        return $uri;
660
    }
661
662
    /**
663
     * Refresh JWT access token.
664
     *
665
     * On success `$this->tokens` data will be updated with new access and renew tokens.
666
     *
667
     * @throws \BadMethodCallException Throws an exception if client has no renew token available.
668
     * @throws \Cake\Network\Exception\ServiceUnavailableException Throws an exception if server response doesn't
669
     *      include the expected data.
670
     * @return void
671
     * @throws BEditaClientException Throws an exception if server response code is not 20x.
672
     */
673
    public function refreshTokens(): void
674
    {
675
        if (empty($this->tokens['renew'])) {
676
            throw new \BadMethodCallException('You must be logged in to renew token');
677
        }
678
679
        $headers = [
680
            'Authorization' => sprintf('Bearer %s', $this->tokens['renew']),
681
        ];
682
683
        $this->sendRequest('POST', '/auth', [], $headers);
684
        $body = $this->getResponseBody();
685
        if (empty($body['meta']['jwt'])) {
686
            throw new BEditaClientException('Invalid response from server');
687
        }
688
689
        $this->setupTokens($body['meta']);
690
    }
691
}
692