Passed
Pull Request — master (#26)
by Edoardo
01:56
created

BEditaClient::getResponseBody()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

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