Passed
Push — master ( 5fb0b3...a1dc53 )
by Dante
01:22
created

BaseClient::setupTokens()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 7
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
     * BEdita API base URL
33
     *
34
     * @var string
35
     */
36
    private $apiBaseUrl = null;
37
38
    /**
39
     * BEdita 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 BEdita 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
     * @return void
203
     * @throws \BEdita\SDK\BEditaClientException Throws an exception if server response code is not 20x.
204
     */
205
    public function refreshTokens(): void
206
    {
207
        if (empty($this->tokens['renew'])) {
208
            throw new \BadMethodCallException('You must be logged in to renew token');
209
        }
210
211
        $headers = [
212
            'Authorization' => sprintf('Bearer %s', $this->tokens['renew']),
213
        ];
214
        $data = ['grant_type' => 'refresh_token'];
215
216
        $this->sendRequest('POST', '/auth', [], $headers, json_encode($data));
217
        $body = $this->getResponseBody();
218
        if (empty($body['meta']['jwt'])) {
219
            throw new BEditaClientException('Invalid response from server');
220
        }
221
222
        $this->setupTokens($body['meta']);
223
    }
224
225
    /**
226
     * Send a generic JSON API request with a basic retry policy on expired token exception.
227
     *
228
     * @param string $method HTTP Method.
229
     * @param string $path Endpoint URL path.
230
     * @param array|null $query Query string parameters.
231
     * @param string[]|null $headers Custom request headers.
232
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
233
     * @return \Psr\Http\Message\ResponseInterface
234
     */
235
    protected function sendRequestRetry(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface
236
    {
237
        try {
238
            return $this->sendRequest($method, $path, $query, $headers, $body);
239
        } catch (BEditaClientException $e) {
240
            // Handle error.
241
            $attributes = $e->getAttributes();
242
            if ($e->getCode() !== 401 || empty($attributes['code']) || $attributes['code'] !== 'be_token_expired') {
243
                // Not an expired token's fault.
244
                throw $e;
245
            }
246
247
            // Refresh and retry.
248
            $this->refreshTokens();
249
            unset($headers['Authorization']);
250
251
            return $this->sendRequest($method, $path, $query, $headers, $body);
252
        }
253
    }
254
255
    /**
256
     * Refresh and retry.
257
     *
258
     * @param string $method HTTP Method.
259
     * @param string $path Endpoint URL path.
260
     * @param array|null $query Query string parameters.
261
     * @param string[]|null $headers Custom request headers.
262
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
263
     * @return \Psr\Http\Message\ResponseInterface
264
     */
265
    protected function refreshAndRetry(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface
266
    {
267
        $this->refreshTokens();
268
        unset($headers['Authorization']);
269
270
        return $this->sendRequest($method, $path, $query, $headers, $body);
271
    }
272
273
    /**
274
     * Send a generic JSON API request and retrieve response $this->response
275
     *
276
     * @param string $method HTTP Method.
277
     * @param string $path Endpoint URL path (with or without starting `/`) or absolute API path
278
     * @param array|null $query Query string parameters.
279
     * @param string[]|null $headers Custom request headers.
280
     * @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body.
281
     * @return \Psr\Http\Message\ResponseInterface
282
     * @throws \BEdita\SDK\BEditaClientException Throws an exception if server response code is not 20x.
283
     */
284
    protected function sendRequest(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface
285
    {
286
        $uri = $this->requestUri($path, $query);
287
        $headers = array_merge($this->defaultHeaders, (array)$headers);
288
289
        // set default `Content-Type` if not set and $body not empty
290
        if (!empty($body)) {
291
            $headers = array_merge($this->defaultContentTypeHeader, $headers);
292
        }
293
294
        // Send the request synchronously to retrieve the response.
295
        // Request and response log performed only if configured via `initLogger()`
296
        $request = new Request($method, $uri, $headers, $body);
297
        $this->logRequest($request);
298
        $this->response = $this->jsonApiClient->sendRequest($request);
299
        $this->logResponse($this->response);
300
        if ($this->getStatusCode() >= 400) {
301
            // Something bad just happened.
302
            $response = $this->getResponseBody();
303
            // Message will be 'error` array, if absent use status massage
304
            $message = empty($response['error']) ? $this->getStatusMessage() : $response['error'];
305
            throw new BEditaClientException($message, $this->getStatusCode());
306
        }
307
308
        return $this->response;
309
    }
310
311
    /**
312
     * Create request URI from path.
313
     * If path is absolute, i.e. it starts with 'http://' or 'https://', path is unchanged.
314
     * Otherwise `$this->apiBaseUrl` is prefixed, prepending a `/` if necessary.
315
     *
316
     * @param string $path Endpoint URL path (with or without starting `/`) or absolute API path
317
     * @param array|null $query Query string parameters.
318
     * @return Uri
319
     */
320
    protected function requestUri(string $path, ?array $query = null): Uri
321
    {
322
        if (strpos($path, 'https://') !== 0 && strpos($path, 'http://') !== 0) {
323
            if (substr($path, 0, 1) !== '/') {
324
                $path = '/' . $path;
325
            }
326
            $path = $this->apiBaseUrl . $path;
327
        }
328
        $uri = new Uri($path);
329
330
        // if path contains query strings, remove them from path and add them to query filter
331
        parse_str($uri->getQuery(), $uriQuery);
332
        if ($query) {
333
            $query = array_merge((array)$uriQuery, (array)$query);
334
            $uri = $uri->withQuery(http_build_query($query));
335
        }
336
337
        return $uri;
338
    }
339
340
    /**
341
     * Unset Authorization from defaultHeaders.
342
     *
343
     * @return void
344
     */
345
    protected function unsetAuthorization(): void
346
    {
347
        if (!array_key_exists('Authorization', $this->defaultHeaders)) {
348
            return;
349
        }
350
        unset($this->defaultHeaders['Authorization']);
351
    }
352
353
    /**
354
     * Send a GET request a list of resources or objects or a single resource or object
355
     *
356
     * @param string $path Endpoint URL path to invoke
357
     * @param array|null $query Optional query string
358
     * @param array|null $headers Headers
359
     * @return array|null Response in array format
360
     */
361
    public function get(string $path, ?array $query = null, ?array $headers = null): ?array
362
    {
363
        $this->sendRequestRetry('GET', $path, $query, $headers);
364
365
        return $this->getResponseBody();
366
    }
367
368
    /**
369
     * Send a PATCH request to modify a single resource or object
370
     *
371
     * @param string $path Endpoint URL path to invoke
372
     * @param mixed $body Request body
373
     * @param array|null $headers Custom request headers
374
     * @return array|null Response in array format
375
     */
376
    public function patch(string $path, $body, ?array $headers = null): ?array
377
    {
378
        $this->sendRequestRetry('PATCH', $path, null, $headers, $body);
379
380
        return $this->getResponseBody();
381
    }
382
383
    /**
384
     * Send a POST request for creating resources or objects or other operations like /auth
385
     *
386
     * @param string $path Endpoint URL path to invoke
387
     * @param mixed $body Request body
388
     * @param array|null $headers Custom request headers
389
     * @return array|null Response in array format
390
     */
391
    public function post(string $path, $body, ?array $headers = null): ?array
392
    {
393
        $this->sendRequestRetry('POST', $path, null, $headers, $body);
394
395
        return $this->getResponseBody();
396
    }
397
398
    /**
399
     * Send a DELETE request
400
     *
401
     * @param string $path Endpoint URL path to invoke.
402
     * @param mixed $body Request body
403
     * @param array|null $headers Custom request headers
404
     * @return array|null Response in array format.
405
     */
406
    public function delete(string $path, $body = null, ?array $headers = null): ?array
407
    {
408
        $this->sendRequestRetry('DELETE', $path, null, $headers, $body);
409
410
        return $this->getResponseBody();
411
    }
412
}
413