Passed
Pull Request — master (#38)
by Dante
01:05
created

BaseClient::get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
c 0
b 0
f 0
nc 1
nop 3
dl 0
loc 5
rs 10
1
<?php
2
declare(strict_types=1);
3
/**
4
 * BEdita, API-first content management framework
5
 * Copyright 2023 Atlas Srl, ChannelWeb Srl, Chialab Srl
6
 *
7
 * Licensed under The MIT License
8
 * For full copyright and license information, please see the LICENSE.txt
9
 * Redistributions of files must retain the above copyright notice.
10
 */
11
12
namespace BEdita\SDK;
13
14
use GuzzleHttp\Psr7\Request;
15
use GuzzleHttp\Psr7\Uri;
16
use Http\Adapter\Guzzle7\Client;
17
use Psr\Http\Message\ResponseInterface;
18
use WoohooLabs\Yang\JsonApi\Client\JsonApiClient;
19
20
class BaseClient
21
{
22
    use LogTrait;
23
24
    /**
25
     * Last response.
26
     *
27
     * @var \Psr\Http\Message\ResponseInterface
28
     */
29
    private $response = null;
30
31
    /**
32
     * BEdita4 API base URL
33
     *
34
     * @var string
35
     */
36
    private $apiBaseUrl = null;
37
38
    /**
39
     * BEdita4 API KEY
40
     *
41
     * @var string
42
     */
43
    private $apiKey = null;
44
45
    /**
46
     * Default headers in request
47
     *
48
     * @var array
49
     */
50
    private $defaultHeaders = [
51
        'Accept' => 'application/vnd.api+json',
52
    ];
53
54
    /**
55
     * Default headers in request
56
     *
57
     * @var array
58
     */
59
    private $defaultContentTypeHeader = [
60
        'Content-Type' => 'application/json',
61
    ];
62
63
    /**
64
     * JWT Auth tokens
65
     *
66
     * @var array
67
     */
68
    private $tokens = [];
69
70
    /**
71
     * JSON API BEdita4 client
72
     *
73
     * @var \WoohooLabs\Yang\JsonApi\Client\JsonApiClient
74
     */
75
    private $jsonApiClient = null;
76
77
    /**
78
     * Setup main client options:
79
     *  - API base URL
80
     *  - API KEY
81
     *  - Auth tokens 'jwt' and 'renew' (optional)
82
     *
83
     * @param string $apiUrl API base URL
84
     * @param string|null $apiKey API key
85
     * @param array $tokens JWT Autorization tokens as associative array ['jwt' => '###', 'renew' => '###']
86
     * @param array $guzzleConfig Additional default configuration for GuzzleHTTP client.
87
     * @return void
88
     */
89
    public function __construct(string $apiUrl, ?string $apiKey = null, array $tokens = [], array $guzzleConfig = [])
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($guzzleConfig);
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
     */
123
    public function getDefaultHeaders(): array
124
    {
125
        return $this->defaultHeaders;
126
    }
127
128
    /**
129
     * Get API base URL used tokens
130
     *
131
     * @return string API base URL
132
     */
133
    public function getApiBaseUrl(): string
134
    {
135
        return $this->apiBaseUrl;
136
    }
137
138
    /**
139
     * Get current used tokens
140
     *
141
     * @return array Current tokens
142
     */
143
    public function getTokens(): array
144
    {
145
        return $this->tokens;
146
    }
147
148
    /**
149
     * Get last HTTP response
150
     *
151
     * @return ResponseInterface|null Response PSR interface
152
     */
153
    public function getResponse(): ?ResponseInterface
154
    {
155
        return $this->response;
156
    }
157
158
    /**
159
     * Get HTTP response status code
160
     * Return null if no response is available
161
     *
162
     * @return int|null Status code.
163
     */
164
    public function getStatusCode(): ?int
165
    {
166
        return $this->response ? $this->response->getStatusCode() : null;
167
    }
168
169
    /**
170
     * Get HTTP response status message
171
     * Return null if no response is available
172
     *
173
     * @return string|null Message related to status code.
174
     */
175
    public function getStatusMessage(): ?string
176
    {
177
        return $this->response ? $this->response->getReasonPhrase() : null;
178
    }
179
180
    /**
181
     * Get response body serialized into a PHP array
182
     *
183
     * @return array|null Response body as PHP array.
184
     */
185
    public function getResponseBody(): ?array
186
    {
187
        $response = $this->getResponse();
188
        if (empty($response)) {
189
            return null;
190
        }
191
        $responseBody = json_decode((string)$response->getBody(), true);
192
193
        return is_array($responseBody) ? $responseBody : null;
194
    }
195
196
    /**
197
     * Refresh JWT access token.
198
     *
199
     * On success `$this->tokens` data will be updated with new access and renew tokens.
200
     *
201
     * @throws \BadMethodCallException Throws an exception if client has no renew token available.
202
     * @throws \Cake\Network\Exception\ServiceUnavailableException Throws an exception if server response doesn't
203
     *      include the expected data.
204
     * @return void
205
     * @throws BEditaClientException Throws an exception if server response code is not 20x.
206
     */
207
    public function refreshTokens(): void
208
    {
209
        if (empty($this->tokens['renew'])) {
210
            throw new \BadMethodCallException('You must be logged in to renew token');
211
        }
212
213
        $headers = [
214
            'Authorization' => sprintf('Bearer %s', $this->tokens['renew']),
215
        ];
216
        $data = ['grant_type' => 'refresh_token'];
217
218
        $this->sendRequest('POST', '/auth', [], $headers, json_encode($data));
219
        $body = $this->getResponseBody();
220
        if (empty($body['meta']['jwt'])) {
221
            throw new BEditaClientException('Invalid response from server');
222
        }
223
224
        $this->setupTokens($body['meta']);
225
    }
226
227
    /**
228
     * Send a generic JSON API request with a basic retry policy on expired token exception.
229
     *
230
     * @param string $method HTTP Method.
231
     * @param string $path Endpoint URL path.
232
     * @param array|null $query Query string parameters.
233
     * @param string[]|null $headers Custom request headers.
234
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
235
     * @return \Psr\Http\Message\ResponseInterface
236
     */
237
    protected function sendRequestRetry(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface
238
    {
239
        try {
240
            return $this->sendRequest($method, $path, $query, $headers, $body);
241
        } catch (BEditaClientException $e) {
242
            // Handle error.
243
            $attributes = $e->getAttributes();
244
            if ($e->getCode() !== 401 || empty($attributes['code']) || $attributes['code'] !== 'be_token_expired') {
245
                // Not an expired token's fault.
246
                throw $e;
247
            }
248
249
            // Refresh and retry.
250
            $this->refreshTokens();
251
            unset($headers['Authorization']);
252
253
            return $this->sendRequest($method, $path, $query, $headers, $body);
254
        }
255
    }
256
257
    /**
258
     * Refresh and retry.
259
     *
260
     * @param string $method HTTP Method.
261
     * @param string $path Endpoint URL path.
262
     * @param array|null $query Query string parameters.
263
     * @param string[]|null $headers Custom request headers.
264
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
265
     * @return \Psr\Http\Message\ResponseInterface
266
     */
267
    protected function refreshAndRetry(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface
268
    {
269
        $this->refreshTokens();
270
        unset($headers['Authorization']);
271
272
        return $this->sendRequest($method, $path, $query, $headers, $body);
273
    }
274
275
    /**
276
     * Send a generic JSON API request and retrieve response $this->response
277
     *
278
     * @param string $method HTTP Method.
279
     * @param string $path Endpoint URL path (with or without starting `/`) or absolute API path
280
     * @param array|null $query Query string parameters.
281
     * @param string[]|null $headers Custom request headers.
282
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
283
     * @return \Psr\Http\Message\ResponseInterface
284
     * @throws BEditaClientException Throws an exception if server response code is not 20x.
285
     */
286
    protected function sendRequest(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface
287
    {
288
        $uri = $this->requestUri($path, $query);
289
        $headers = array_merge($this->defaultHeaders, (array)$headers);
290
291
        // set default `Content-Type` if not set and $body not empty
292
        if (!empty($body)) {
293
            $headers = array_merge($this->defaultContentTypeHeader, $headers);
294
        }
295
296
        // Send the request synchronously to retrieve the response.
297
        // Request and response log performed only if configured via `initLogger()`
298
        $request = new Request($method, $uri, $headers, $body);
299
        $this->logRequest($request);
300
        $this->response = $this->jsonApiClient->sendRequest($request);
301
        $this->logResponse($this->response);
302
        if ($this->getStatusCode() >= 400) {
303
            // Something bad just happened.
304
            $response = $this->getResponseBody();
305
            // Message will be 'error` array, if absent use status massage
306
            $message = empty($response['error']) ? $this->getStatusMessage() : $response['error'];
307
            throw new BEditaClientException($message, $this->getStatusCode());
308
        }
309
310
        return $this->response;
311
    }
312
313
    /**
314
     * Create request URI from path.
315
     * If path is absolute, i.e. it starts with 'http://' or 'https://', path is unchanged.
316
     * Otherwise `$this->apiBaseUrl` is prefixed, prepending a `/` if necessary.
317
     *
318
     * @param string $path Endpoint URL path (with or without starting `/`) or absolute API path
319
     * @param array|null $query Query string parameters.
320
     * @return Uri
321
     */
322
    protected function requestUri(string $path, ?array $query = null): Uri
323
    {
324
        if (strpos($path, 'https://') !== 0 && strpos($path, 'http://') !== 0) {
325
            if (substr($path, 0, 1) !== '/') {
326
                $path = '/' . $path;
327
            }
328
            $path = $this->apiBaseUrl . $path;
329
        }
330
        $uri = new Uri($path);
331
332
        // if path contains query strings, remove them from path and add them to query filter
333
        parse_str($uri->getQuery(), $uriQuery);
334
        if ($query) {
335
            $query = array_merge((array)$uriQuery, (array)$query);
336
            $uri = $uri->withQuery(http_build_query($query));
337
        }
338
339
        return $uri;
340
    }
341
342
    /**
343
     * Unset Authorization from defaultHeaders.
344
     *
345
     * @return void
346
     */
347
    protected function unsetAuthorization(): void
348
    {
349
        if (!array_key_exists('Authorization', $this->defaultHeaders)) {
350
            return;
351
        }
352
        unset($this->defaultHeaders['Authorization']);
353
    }
354
355
    /**
356
     * Send a GET request a list of resources or objects or a single resource or object
357
     *
358
     * @param string $path Endpoint URL path to invoke
359
     * @param array|null $query Optional query string
360
     * @param array|null $headers Headers
361
     * @return array|null Response in array format
362
     */
363
    public function get(string $path, ?array $query = null, ?array $headers = null): ?array
364
    {
365
        $this->sendRequestRetry('GET', $path, $query, $headers);
366
367
        return $this->getResponseBody();
368
    }
369
370
    /**
371
     * Send a PATCH request to modify a single resource or object
372
     *
373
     * @param string $path Endpoint URL path to invoke
374
     * @param mixed $body Request body
375
     * @param array|null $headers Custom request headers
376
     * @return array|null Response in array format
377
     */
378
    public function patch(string $path, $body, ?array $headers = null): ?array
379
    {
380
        $this->sendRequestRetry('PATCH', $path, null, $headers, $body);
381
382
        return $this->getResponseBody();
383
    }
384
385
    /**
386
     * Send a POST request for creating resources or objects or other operations like /auth
387
     *
388
     * @param string $path Endpoint URL path to invoke
389
     * @param mixed $body Request body
390
     * @param array|null $headers Custom request headers
391
     * @return array|null Response in array format
392
     */
393
    public function post(string $path, $body, ?array $headers = null): ?array
394
    {
395
        $this->sendRequestRetry('POST', $path, null, $headers, $body);
396
397
        return $this->getResponseBody();
398
    }
399
400
    /**
401
     * Send a DELETE request
402
     *
403
     * @param string $path Endpoint URL path to invoke.
404
     * @param mixed $body Request body
405
     * @param array|null $headers Custom request headers
406
     * @return array|null Response in array format.
407
     */
408
    public function delete(string $path, $body = null, ?array $headers = null): ?array
409
    {
410
        $this->sendRequestRetry('DELETE', $path, null, $headers, $body);
411
412
        return $this->getResponseBody();
413
    }
414
}
415