Completed
Push — master ( bfbc7e...1e01d6 )
by Dante
20s queued 10s
created

BEditaClient::mapItemsAndMeta()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 13
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 19
rs 9.8333

1 Method

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