Completed
Push — master ( 0901cd...646a06 )
by Stefano
13s queued 10s
created

BEditaClient   C

Complexity

Total Complexity 56

Size/Duplication

Total Lines 602
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 56
dl 0
loc 602
rs 5.5333
c 0
b 0
f 0

30 Methods

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

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
25
    /**
26
     * Last response.
27
     *
28
     * @var \Psr\Http\Message\ResponseInterface
29
     */
30
    private $response = null;
31
32
    /**
33
     * BEdita4 API base URL
34
     *
35
     * @var string
36
     */
37
    private $apiBaseUrl = null;
38
39
    /**
40
     * BEdita4 API KEY
41
     *
42
     * @var string
43
     */
44
    private $apiKey = null;
45
46
    /**
47
     * Default headers in request
48
     *
49
     * @var array
50
     */
51
    private $defaultHeaders = [
52
        'Accept' => 'application/vnd.api+json',
53
    ];
54
55
    /**
56
     * Default headers in request
57
     *
58
     * @var array
59
     */
60
    private $defaultContentTypeHeader = [
61
        'Content-Type' => 'application/json',
62
    ];
63
64
    /**
65
     * JWT Auth tokens
66
     *
67
     * @var array
68
     */
69
    private $tokens = [];
70
71
    /**
72
     * JSON API BEdita4 client
73
     *
74
     * @var \WoohooLabs\Yang\JsonApi\Client\JsonApiClient
75
     */
76
    private $jsonApiClient = null;
77
78
    /**
79
     * Setup main client options:
80
     *  - API base URL
81
     *  - API KEY
82
     *  - Auth tokens 'jwt' and 'renew' (optional)
83
     *
84
     * @param string $apiUrl API base URL
85
     * @param string $apiKey API key
86
     * @param array $tokens JWT Autorization tokens as associative array ['jwt' => '###', 'renew' => '###']
87
     * @return void
88
     */
89
    public function __construct(string $apiUrl, ?string $apiKey = null, array $tokens = [])
90
    {
91
        $this->apiBaseUrl = $apiUrl;
92
        $this->apiKey = $apiKey;
93
94
        $this->defaultHeaders['X-Api-Key'] = $this->apiKey;
95
        $this->setupTokens($tokens);
96
97
        // setup an asynchronous JSON API client
98
        $guzzleClient = Client::createWithConfig([]);
99
        $this->jsonApiClient = new JsonApiClient($guzzleClient);
100
    }
101
102
    /**
103
     * Setup JWT access and refresh tokens.
104
     *
105
     * @param array $tokens JWT tokens as associative array ['jwt' => '###', 'renew' => '###']
106
     * @return void
107
     */
108
    public function setupTokens(array $tokens) : void
109
    {
110
        $this->tokens = $tokens;
111
        if (!empty($tokens['jwt'])) {
112
            $this->defaultHeaders['Authorization'] = sprintf('Bearer %s', $tokens['jwt']);
113
        } else {
114
            unset($this->defaultHeaders['Authorization']);
115
        }
116
    }
117
118
    /**
119
     * Get default headers in use on every request
120
     *
121
     * @return array Default headers
122
     * @codeCoverageIgnore
123
     */
124
    public function getDefaultHeaders() : array
125
    {
126
        return $this->defaultHeaders;
127
    }
128
129
    /**
130
     * Get API base URL used tokens
131
     *
132
     * @return string API base URL
133
     * @codeCoverageIgnore
134
     */
135
    public function getApiBaseUrl() : string
136
    {
137
        return $this->apiBaseUrl;
138
    }
139
140
    /**
141
     * Get current used tokens
142
     *
143
     * @return array Current tokens
144
     * @codeCoverageIgnore
145
     */
146
    public function getTokens() : array
147
    {
148
        return $this->tokens;
149
    }
150
151
    /**
152
     * Get last HTTP response
153
     *
154
     * @return ResponseInterface|null Response PSR interface
155
     * @codeCoverageIgnore
156
     */
157
    public function getResponse() : ?ResponseInterface
158
    {
159
        return $this->response;
160
    }
161
162
    /**
163
     * Get HTTP response status code
164
     * Return null if no response is available
165
     *
166
     * @return int|null Status code.
167
     */
168
    public function getStatusCode() : ?int
169
    {
170
        return $this->response ? $this->response->getStatusCode() : null;
171
    }
172
173
    /**
174
     * Get HTTP response status message
175
     * Return null if no response is available
176
     *
177
     * @return string|null Message related to status code.
178
     */
179
    public function getStatusMessage() : ?string
180
    {
181
        return $this->response ? $this->response->getReasonPhrase() : null;
182
    }
183
184
    /**
185
     * Get response body serialized into a PHP array
186
     *
187
     * @return array|null Response body as PHP array.
188
     */
189
    public function getResponseBody() : ?array
190
    {
191
        $response = $this->getResponse();
192
        if (empty($response)) {
193
            return null;
194
        }
195
        $responseBody = json_decode((string)$response->getBody(), true);
196
        if (!is_array($responseBody)) {
197
            return null;
198
        }
199
200
        return $responseBody;
201
    }
202
203
    /**
204
     * Classic authentication via POST /auth using username and password
205
     *
206
     * @param string $username username
207
     * @param string $password password
208
     * @return array|null Response in array format
209
     */
210
    public function authenticate(string $username, string $password) : ?array
211
    {
212
        $body = json_encode(compact('username', 'password'));
213
214
        return $this->post('/auth', $body, ['Content-Type' => 'application/json']);
215
    }
216
217
    /**
218
     * Send a GET request a list of resources or objects or a single resource or object
219
     *
220
     * @param string $path Endpoint URL path to invoke
221
     * @param array|null $query Optional query string
222
     * @param array|null $headers Headers
223
     * @return array|null Response in array format
224
     */
225
    public function get(string $path, ?array $query = null, ?array $headers = null) : ?array
226
    {
227
        $this->sendRequestRetry('GET', $path, $query, $headers);
228
229
        return $this->getResponseBody();
230
    }
231
232
    /**
233
     * GET a list of objects of a given type
234
     *
235
     * @param string $type Object type name
236
     * @param array|null $query Optional query string
237
     * @param array|null $headers Custom request headers
238
     * @return array|null Response in array format
239
     */
240
    public function getObjects(string $type = 'objects', ?array $query = null, ?array $headers = null) : ?array
241
    {
242
        return $this->get(sprintf('/%s', $type), $query, $headers);
243
    }
244
245
    /**
246
     * GET a single object of a given type
247
     *
248
     * @param int|string $id Object id
249
     * @param string $type Object type name
250
     * @param array|null $query Optional query string
251
     * @param array|null $headers Custom request headers
252
     * @return array|null Response in array format
253
     */
254
    public function getObject($id, string $type = 'objects', ?array $query = null, ?array $headers = null) : ?array
255
    {
256
        return $this->get(sprintf('/%s/%s', $type, $id), $query, $headers);
257
    }
258
259
    /**
260
     * GET a list of related objects
261
     *
262
     * @param int|string $id Object id
263
     * @param string $type Object type name
264
     * @param string $relation Relation name
265
     * @param array|null $query Optional query string
266
     * @param array|null $headers Custom request headers
267
     * @return array|null Response in array format
268
     */
269
    public function getRelated($id, string $type, string $relation, ?array $query = null, ?array $headers = null) : ?array
270
    {
271
        return $this->get(sprintf('/%s/%s/%s', $type, $id, $relation), $query, $headers);
272
    }
273
274
    /**
275
     * Add a list of related objects
276
     *
277
     * @param int|string $id Object id
278
     * @param string $type Object type name
279
     * @param string $relation Relation name
280
     * @param string $data Related objects to add, MUST contain id and type
281
     * @param array|null $headers Custom request headers
282
     * @return array|null Response in array format
283
     */
284
    public function addRelated($id, string $type, string $relation, array $data, ?array $headers = null) : ?array
285
    {
286
        $body = compact('data');
287
288
        return $this->post(sprintf('/%s/%s/relationships/%s', $type, $id, $relation), json_encode($body), $headers);
289
    }
290
291
    /**
292
     * DELETE a list of related objects
293
     *
294
     * @param int|string $id Object id
295
     * @param string $type Object type name
296
     * @param string $relation Relation name
297
     * @param string $data Related objects to remove from relation
298
     * @param array|null $headers Custom request headers
299
     * @return array|null Response in array format
300
     */
301
    public function removeRelated($id, string $type, string $relation, array $data, ?array $headers = null) : ?array
302
    {
303
        $body = compact('data');
304
305
        return $this->delete(sprintf('/%s/%s/relationships/%s', $type, $id, $relation), json_encode($body), $headers);
306
    }
307
308
    /**
309
     * Create a new object (POST) or modify an existing one (PATCH)
310
     *
311
     * @param string $type Object type name
312
     * @param array $data Object data to save
313
     * @param array|null $headers Custom request headers
314
     * @return array|null Response in array format
315
     */
316
    public function saveObject(string $type, array $data, ?array $headers = null) : ?array
317
    {
318
        $id = null;
319
        if (array_key_exists('id', $data)) {
320
            $id = $data['id'];
321
            unset($data['id']);
322
        }
323
324
        $body = [
325
            'data' => [
326
                'type' => $type,
327
                'attributes' => $data,
328
            ],
329
        ];
330
        if (!$id) {
331
            return $this->post(sprintf('/%s', $type), json_encode($body), $headers);
332
        }
333
        $body['data']['id'] = $id;
334
335
        return $this->patch(sprintf('/%s/%s', $type, $id), json_encode($body), $headers);
336
    }
337
338
    /**
339
     * Delete an object (DELETE) => move to trashcan.
340
     *
341
     * @param int|string $id Object id
342
     * @param string $type Object type name
343
     * @return array|null Response in array format
344
     */
345
    public function deleteObject($id, string $type) : ?array
346
    {
347
        return $this->delete(sprintf('/%s/%s', $type, $id));
348
    }
349
350
    /**
351
     * Remove an object => permanently remove object from trashcan.
352
     *
353
     * @param int|string $id Object id
354
     * @return array|null Response in array format
355
     */
356
    public function remove($id) : ?array
357
    {
358
        return $this->delete(sprintf('/trash/%s', $id));
359
    }
360
361
    /**
362
     * Upload file (POST)
363
     *
364
     * @param string $filename The file name
365
     * @param string $filepath File full path: could be on a local filesystem or a remote reachable URL
366
     * @param array|null $headers Custom request headers
367
     * @return array|null Response in array format
368
     * @throws BEditaClientException
369
     */
370
    public function upload($filename, $filepath, ?array $headers = null) : ?array
371
    {
372
        if (!file_exists($filepath)) {
373
            throw new BEditaClientException('File not found', 500);
374
        }
375
        $file = file_get_contents($filepath);
376
        if (!$file) {
377
            throw new BEditaClientException('File get contents failed', 500);
378
        }
379
        if (empty($headers['Content-Type'])) {
380
            $headers['Content-Type'] = mime_content_type($filepath);
381
        }
382
383
        return $this->post(sprintf('/streams/upload/%s', $filename), $file, $headers);
384
    }
385
386
    /**
387
     * Create media by type and body data and link it to a stream:
388
     *  - `POST /:type` with `$body` as payload, create media object
389
     *  - `PATCH /streams/:stream_id/relationships/object` modify stream adding relation to media
390
     *  - `GET /:type/:id` get media data
391
     *
392
     * @param string $streamId The stream identifier
393
     * @param string $type The type
394
     * @param array $body The body data
395
     * @return array|null Response in array format
396
     * @throws BEditaClientException
397
     */
398
    public function createMediaFromStream($streamId, $type, $body) : array
399
    {
400
        $response = $this->post(sprintf('/%s', $type), json_encode($body));
401
        if (empty($response)) {
402
            throw new BEditaClientException('Invalid response from POST ' . sprintf('/%s', $type));
403
        }
404
        $id = $response['data']['id'];
405
        $data = compact('id', 'type');
406
        $body = compact('data');
407
        $response = $this->patch(sprintf('/streams/%s/relationships/object', $streamId), json_encode($body));
408
        if (empty($response)) {
409
            throw new BEditaClientException('Invalid response from PATCH ' . sprintf('/streams/%s/relationships/object', $id));
410
        }
411
412
        return $this->getObject($data['id'], $data['type']);
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->getObject(...a['id'], $data['type']) could return the type null which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
413
    }
414
415
    /**
416
     * Thumbnail request using `GET /media/thumbs` endpoint
417
     *
418
     *  Usage:
419
     *          thumbs(123) => `GET /media/thumbs/123`
420
     *          thumbs(123, ['preset' => 'glide']) => `GET /media/thumbs/123&preset=glide`
421
     *          thumbs(null, ['ids' => '123,124,125']) => `GET /media/thumbs?ids=123,124,125`
422
     *          thumbs(null, ['ids' => '123,124,125', 'preset' => 'async']) => `GET /media/thumbs?ids=123,124,125&preset=async`
423
     *          thumbs(123, ['w' => 100, 'h' => 80, 'fm' => 'jpg']) => `GET /media/thumbs/123/w=100&h=80&fm=jpg` (these options could be not available... just set in preset(s))
424
     *
425
     * @param int|null $id the media Id.
426
     * @param array $query The query params for thumbs call.
427
     * @return array|null Response in array format
428
     */
429
    public function thumbs($id = null, $query = []) : ?array
430
    {
431
        if (empty($id) && empty($query['ids'])) {
432
            throw new BEditaClientException('Invalid empty id|ids for thumbs');
433
        }
434
        $endpoint = '/media/thumbs';
435
        if (!empty($id)) {
436
            $endpoint .= sprintf('/%d', $id);
437
        }
438
439
        return $this->get($endpoint, $query);
440
    }
441
442
    /**
443
     * Get JSON SCHEMA of a resource or object
444
     *
445
     * @param string $type Object or resource type name
446
     * @return array|null JSON SCHEMA in array format
447
     */
448
    public function schema(string $type) : ?array
449
    {
450
        $h = ['Accept' => 'application/schema+json'];
451
452
        return $this->get(sprintf('/model/schema/%s', $type), null, $h);
453
    }
454
455
    /**
456
     * Restore object from trash
457
     *
458
     * @param int|string $id Object id
459
     * @param string $type Object type name
460
     * @return array|null Response in array format
461
     */
462
    public function restoreObject($id, string $type) : ?array
463
    {
464
        $body = [
465
            'data' => [
466
                'id' => $id,
467
                'type' => $type,
468
            ],
469
        ];
470
471
        return $this->patch(sprintf('/%s/%s', 'trash', $id), json_encode($body));
472
    }
473
474
    /**
475
     * Send a PATCH request to modify a single resource or object
476
     *
477
     * @param string $path Endpoint URL path to invoke
478
     * @param mixed $body Request body
479
     * @param array|null $headers Custom request headers
480
     * @return array|null Response in array format
481
     */
482
    public function patch(string $path, $body, ?array $headers = null) : ?array
483
    {
484
        $this->sendRequestRetry('PATCH', $path, null, $headers, $body);
485
486
        return $this->getResponseBody();
487
    }
488
489
    /**
490
     * Send a POST request for creating resources or objects or other operations like /auth
491
     *
492
     * @param string $path Endpoint URL path to invoke
493
     * @param mixed $body Request body
494
     * @param array|null $headers Custom request headers
495
     * @return array|null Response in array format
496
     */
497
    public function post(string $path, $body, ?array $headers = null) : ?array
498
    {
499
        $this->sendRequestRetry('POST', $path, null, $headers, $body);
500
501
        return $this->getResponseBody();
502
    }
503
504
    /**
505
     * Send a DELETE request
506
     *
507
     * @param string $path Endpoint URL path to invoke.
508
     * @param mixed $body Request body
509
     * @param array|null $headers Custom request headers
510
     * @return array|null Response in array format.
511
     */
512
    public function delete(string $path, $body = null, ?array $headers = null) : ?array
513
    {
514
        $this->sendRequestRetry('DELETE', $path, null, $headers, $body);
515
516
        return $this->getResponseBody();
517
    }
518
519
    /**
520
     * Send a generic JSON API request with a basic retry policy on expired token exception.
521
     *
522
     * @param string $method HTTP Method.
523
     * @param string $path Endpoint URL path.
524
     * @param array|null $query Query string parameters.
525
     * @param string[]|null $headers Custom request headers.
526
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
527
     * @return \Psr\Http\Message\ResponseInterface
528
     */
529
    protected function sendRequestRetry(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null) : ResponseInterface
530
    {
531
        try {
532
            return $this->sendRequest($method, $path, $query, $headers, $body);
533
        } catch (BEditaClientException $e) {
534
            // Handle error.
535
            $attributes = $e->getAttributes();
536
            if ($e->getCode() !== 401 || empty($attributes['code']) || $attributes['code'] !== 'be_token_expired') {
537
                // Not an expired token's fault.
538
                throw $e;
539
            }
540
541
            // Refresh and retry.
542
            $this->refreshTokens();
543
            unset($headers['Authorization']);
544
545
            return $this->sendRequest($method, $path, $query, $headers, $body);
546
        }
547
    }
548
549
    /**
550
     * Send a generic JSON API request and retrieve response $this->response
551
     *
552
     * @param string $method HTTP Method.
553
     * @param string $path Endpoint URL path.
554
     * @param array|null $query Query string parameters.
555
     * @param string[]|null $headers Custom request headers.
556
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
557
     * @return \Psr\Http\Message\ResponseInterface
558
     * @throws BEditaClientException Throws an exception if server response code is not 20x.
559
     */
560
    protected function sendRequest(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null) : ResponseInterface
561
    {
562
        $uri = new Uri($this->apiBaseUrl);
563
        $uri = $uri->withPath($uri->getPath() . '/' . $path);
564
        if ($query) {
565
            $uri = $uri->withQuery(http_build_query((array)$query));
566
        }
567
        $headers = array_merge($this->defaultHeaders, (array)$headers);
568
569
        // set default `Content-Type` if not set and $body not empty
570
        if (!empty($body)) {
571
            $headers = array_merge($this->defaultContentTypeHeader, $headers);
572
        }
573
574
        // Send the request synchronously to retrieve the response.
575
        $this->response = $this->jsonApiClient->sendRequest(new Request($method, $uri, $headers, $body));
576
        if ($this->getStatusCode() >= 400) {
577
            // Something bad just happened.
578
            $statusCode = $this->getStatusCode();
579
            $response = $this->getResponseBody();
580
581
            $code = (string)$statusCode;
582
            $reason = $this->getStatusMessage();
583
            if (!empty($response['error']['code'])) {
584
                $code = $response['error']['code'];
585
            }
586
            if (!empty($response['error']['title'])) {
587
                $reason = $response['error']['title'];
588
            }
589
590
            throw new BEditaClientException(compact('code', 'reason'), $statusCode);
591
        }
592
593
        return $this->response;
594
    }
595
596
    /**
597
     * Refresh JWT access token.
598
     *
599
     * On success `$this->tokens` data will be updated with new access and renew tokens.
600
     *
601
     * @throws \BadMethodCallException Throws an exception if client has no renew token available.
602
     * @throws \Cake\Network\Exception\ServiceUnavailableException Throws an exception if server response doesn't
603
     *      include the expected data.
604
     * @return void
605
     * @throws BEditaClientException Throws an exception if server response code is not 20x.
606
     */
607
    public function refreshTokens() : void
608
    {
609
        if (empty($this->tokens['renew'])) {
610
            throw new \BadMethodCallException('You must be logged in to renew token');
611
        }
612
613
        $headers = [
614
            'Authorization' => sprintf('Bearer %s', $this->tokens['renew']),
615
        ];
616
617
        $this->sendRequest('POST', '/auth', [], $headers);
618
        $body = $this->getResponseBody();
619
        if (empty($body['meta']['jwt'])) {
620
            throw new BEditaClientException('Invalid response from server');
621
        }
622
623
        $this->setupTokens($body['meta']);
624
    }
625
}
626