|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* BEdita, API-first content management framework |
|
4
|
|
|
* Copyright 2022 Atlas Srl, 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\Guzzle7\Client; |
|
16
|
|
|
use Psr\Http\Message\ResponseInterface; |
|
17
|
|
|
use WoohooLabs\Yang\JsonApi\Client\JsonApiClient; |
|
18
|
|
|
|
|
19
|
|
|
class BaseClient |
|
20
|
|
|
{ |
|
21
|
|
|
use LogTrait; |
|
22
|
|
|
|
|
23
|
|
|
/** |
|
24
|
|
|
* Last response. |
|
25
|
|
|
* |
|
26
|
|
|
* @var \Psr\Http\Message\ResponseInterface |
|
27
|
|
|
*/ |
|
28
|
|
|
private $response = null; |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* BEdita4 API base URL |
|
32
|
|
|
* |
|
33
|
|
|
* @var string |
|
34
|
|
|
*/ |
|
35
|
|
|
private $apiBaseUrl = null; |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* BEdita4 API KEY |
|
39
|
|
|
* |
|
40
|
|
|
* @var string |
|
41
|
|
|
*/ |
|
42
|
|
|
private $apiKey = null; |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Default headers in request |
|
46
|
|
|
* |
|
47
|
|
|
* @var array |
|
48
|
|
|
*/ |
|
49
|
|
|
private $defaultHeaders = [ |
|
50
|
|
|
'Accept' => 'application/vnd.api+json', |
|
51
|
|
|
]; |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* Default headers in request |
|
55
|
|
|
* |
|
56
|
|
|
* @var array |
|
57
|
|
|
*/ |
|
58
|
|
|
private $defaultContentTypeHeader = [ |
|
59
|
|
|
'Content-Type' => 'application/json', |
|
60
|
|
|
]; |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* JWT Auth tokens |
|
64
|
|
|
* |
|
65
|
|
|
* @var array |
|
66
|
|
|
*/ |
|
67
|
|
|
private $tokens = []; |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* JSON API BEdita4 client |
|
71
|
|
|
* |
|
72
|
|
|
* @var \WoohooLabs\Yang\JsonApi\Client\JsonApiClient |
|
73
|
|
|
*/ |
|
74
|
|
|
private $jsonApiClient = null; |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* Setup main client options: |
|
78
|
|
|
* - API base URL |
|
79
|
|
|
* - API KEY |
|
80
|
|
|
* - Auth tokens 'jwt' and 'renew' (optional) |
|
81
|
|
|
* |
|
82
|
|
|
* @param string $apiUrl API base URL |
|
83
|
|
|
* @param string|null $apiKey API key |
|
84
|
|
|
* @param array $tokens JWT Autorization tokens as associative array ['jwt' => '###', 'renew' => '###'] |
|
85
|
|
|
* @param array $guzzleConfig Additional default configuration for GuzzleHTTP client. |
|
86
|
|
|
* @return void |
|
87
|
|
|
*/ |
|
88
|
|
|
public function __construct(string $apiUrl, ?string $apiKey = null, array $tokens = [], array $guzzleConfig = []) |
|
89
|
|
|
{ |
|
90
|
|
|
$this->apiBaseUrl = $apiUrl; |
|
91
|
|
|
$this->apiKey = $apiKey; |
|
92
|
|
|
|
|
93
|
|
|
$this->defaultHeaders['X-Api-Key'] = $this->apiKey; |
|
94
|
|
|
$this->setupTokens($tokens); |
|
95
|
|
|
|
|
96
|
|
|
// setup an asynchronous JSON API client |
|
97
|
|
|
$guzzleClient = Client::createWithConfig($guzzleConfig); |
|
98
|
|
|
$this->jsonApiClient = new JsonApiClient($guzzleClient); |
|
99
|
|
|
} |
|
100
|
|
|
|
|
101
|
|
|
/** |
|
102
|
|
|
* Setup JWT access and refresh tokens. |
|
103
|
|
|
* |
|
104
|
|
|
* @param array $tokens JWT tokens as associative array ['jwt' => '###', 'renew' => '###'] |
|
105
|
|
|
* @return void |
|
106
|
|
|
*/ |
|
107
|
|
|
public function setupTokens(array $tokens): void |
|
108
|
|
|
{ |
|
109
|
|
|
$this->tokens = $tokens; |
|
110
|
|
|
if (!empty($tokens['jwt'])) { |
|
111
|
|
|
$this->defaultHeaders['Authorization'] = sprintf('Bearer %s', $tokens['jwt']); |
|
112
|
|
|
} else { |
|
113
|
|
|
unset($this->defaultHeaders['Authorization']); |
|
114
|
|
|
} |
|
115
|
|
|
} |
|
116
|
|
|
|
|
117
|
|
|
/** |
|
118
|
|
|
* Get default headers in use on every request |
|
119
|
|
|
* |
|
120
|
|
|
* @return array Default headers |
|
121
|
|
|
* @codeCoverageIgnore |
|
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
|
|
|
* @codeCoverageIgnore |
|
133
|
|
|
*/ |
|
134
|
|
|
public function getApiBaseUrl(): string |
|
135
|
|
|
{ |
|
136
|
|
|
return $this->apiBaseUrl; |
|
137
|
|
|
} |
|
138
|
|
|
|
|
139
|
|
|
/** |
|
140
|
|
|
* Get current used tokens |
|
141
|
|
|
* |
|
142
|
|
|
* @return array Current tokens |
|
143
|
|
|
* @codeCoverageIgnore |
|
144
|
|
|
*/ |
|
145
|
|
|
public function getTokens(): array |
|
146
|
|
|
{ |
|
147
|
|
|
return $this->tokens; |
|
148
|
|
|
} |
|
149
|
|
|
|
|
150
|
|
|
/** |
|
151
|
|
|
* Get last HTTP response |
|
152
|
|
|
* |
|
153
|
|
|
* @return ResponseInterface|null Response PSR interface |
|
154
|
|
|
* @codeCoverageIgnore |
|
155
|
|
|
*/ |
|
156
|
|
|
public function getResponse(): ?ResponseInterface |
|
157
|
|
|
{ |
|
158
|
|
|
return $this->response; |
|
159
|
|
|
} |
|
160
|
|
|
|
|
161
|
|
|
/** |
|
162
|
|
|
* Get HTTP response status code |
|
163
|
|
|
* Return null if no response is available |
|
164
|
|
|
* |
|
165
|
|
|
* @return int|null Status code. |
|
166
|
|
|
*/ |
|
167
|
|
|
public function getStatusCode(): ?int |
|
168
|
|
|
{ |
|
169
|
|
|
return $this->response ? $this->response->getStatusCode() : null; |
|
170
|
|
|
} |
|
171
|
|
|
|
|
172
|
|
|
/** |
|
173
|
|
|
* Get HTTP response status message |
|
174
|
|
|
* Return null if no response is available |
|
175
|
|
|
* |
|
176
|
|
|
* @return string|null Message related to status code. |
|
177
|
|
|
*/ |
|
178
|
|
|
public function getStatusMessage(): ?string |
|
179
|
|
|
{ |
|
180
|
|
|
return $this->response ? $this->response->getReasonPhrase() : null; |
|
181
|
|
|
} |
|
182
|
|
|
|
|
183
|
|
|
/** |
|
184
|
|
|
* Get response body serialized into a PHP array |
|
185
|
|
|
* |
|
186
|
|
|
* @return array|null Response body as PHP array. |
|
187
|
|
|
*/ |
|
188
|
|
|
public function getResponseBody(): ?array |
|
189
|
|
|
{ |
|
190
|
|
|
$response = $this->getResponse(); |
|
191
|
|
|
if (empty($response)) { |
|
192
|
|
|
return null; |
|
193
|
|
|
} |
|
194
|
|
|
$responseBody = json_decode((string)$response->getBody(), true); |
|
195
|
|
|
if (!is_array($responseBody)) { |
|
196
|
|
|
return null; |
|
197
|
|
|
} |
|
198
|
|
|
|
|
199
|
|
|
return $responseBody; |
|
200
|
|
|
} |
|
201
|
|
|
|
|
202
|
|
|
/** |
|
203
|
|
|
* Refresh JWT access token. |
|
204
|
|
|
* |
|
205
|
|
|
* On success `$this->tokens` data will be updated with new access and renew tokens. |
|
206
|
|
|
* |
|
207
|
|
|
* @throws \BadMethodCallException Throws an exception if client has no renew token available. |
|
208
|
|
|
* @throws \Cake\Network\Exception\ServiceUnavailableException Throws an exception if server response doesn't |
|
209
|
|
|
* include the expected data. |
|
210
|
|
|
* @return void |
|
211
|
|
|
* @throws BEditaClientException Throws an exception if server response code is not 20x. |
|
212
|
|
|
*/ |
|
213
|
|
|
public function refreshTokens(): void |
|
214
|
|
|
{ |
|
215
|
|
|
if (empty($this->tokens['renew'])) { |
|
216
|
|
|
throw new \BadMethodCallException('You must be logged in to renew token'); |
|
217
|
|
|
} |
|
218
|
|
|
|
|
219
|
|
|
$headers = [ |
|
220
|
|
|
'Authorization' => sprintf('Bearer %s', $this->tokens['renew']), |
|
221
|
|
|
]; |
|
222
|
|
|
|
|
223
|
|
|
$this->sendRequest('POST', '/auth', [], $headers); |
|
224
|
|
|
$body = $this->getResponseBody(); |
|
225
|
|
|
if (empty($body['meta']['jwt'])) { |
|
226
|
|
|
throw new BEditaClientException('Invalid response from server'); |
|
227
|
|
|
} |
|
228
|
|
|
|
|
229
|
|
|
$this->setupTokens($body['meta']); |
|
230
|
|
|
} |
|
231
|
|
|
|
|
232
|
|
|
/** |
|
233
|
|
|
* Send a generic JSON API request with a basic retry policy on expired token exception. |
|
234
|
|
|
* |
|
235
|
|
|
* @param string $method HTTP Method. |
|
236
|
|
|
* @param string $path Endpoint URL path. |
|
237
|
|
|
* @param array|null $query Query string parameters. |
|
238
|
|
|
* @param string[]|null $headers Custom request headers. |
|
239
|
|
|
* @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body. |
|
240
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
|
241
|
|
|
*/ |
|
242
|
|
|
protected function sendRequestRetry(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface |
|
243
|
|
|
{ |
|
244
|
|
|
try { |
|
245
|
|
|
return $this->sendRequest($method, $path, $query, $headers, $body); |
|
246
|
|
|
} catch (BEditaClientException $e) { |
|
247
|
|
|
// Handle error. |
|
248
|
|
|
$attributes = $e->getAttributes(); |
|
249
|
|
|
if ($e->getCode() !== 401 || empty($attributes['code']) || $attributes['code'] !== 'be_token_expired') { |
|
250
|
|
|
// Not an expired token's fault. |
|
251
|
|
|
throw $e; |
|
252
|
|
|
} |
|
253
|
|
|
|
|
254
|
|
|
// Refresh and retry. |
|
255
|
|
|
$this->refreshTokens(); |
|
256
|
|
|
unset($headers['Authorization']); |
|
257
|
|
|
|
|
258
|
|
|
return $this->sendRequest($method, $path, $query, $headers, $body); |
|
259
|
|
|
} |
|
260
|
|
|
} |
|
261
|
|
|
|
|
262
|
|
|
/** |
|
263
|
|
|
* Send a generic JSON API request and retrieve response $this->response |
|
264
|
|
|
* |
|
265
|
|
|
* @param string $method HTTP Method. |
|
266
|
|
|
* @param string $path Endpoint URL path (with or without starting `/`) or absolute API path |
|
267
|
|
|
* @param array|null $query Query string parameters. |
|
268
|
|
|
* @param string[]|null $headers Custom request headers. |
|
269
|
|
|
* @param string|resource|\Psr\Http\Message\StreamInterface|null $body Request body. |
|
270
|
|
|
* @return \Psr\Http\Message\ResponseInterface |
|
271
|
|
|
* @throws BEditaClientException Throws an exception if server response code is not 20x. |
|
272
|
|
|
*/ |
|
273
|
|
|
protected function sendRequest(string $method, string $path, ?array $query = null, ?array $headers = null, $body = null): ResponseInterface |
|
274
|
|
|
{ |
|
275
|
|
|
$uri = $this->requestUri($path, $query); |
|
276
|
|
|
$headers = array_merge($this->defaultHeaders, (array)$headers); |
|
277
|
|
|
|
|
278
|
|
|
// set default `Content-Type` if not set and $body not empty |
|
279
|
|
|
if (!empty($body)) { |
|
280
|
|
|
$headers = array_merge($this->defaultContentTypeHeader, $headers); |
|
281
|
|
|
} |
|
282
|
|
|
|
|
283
|
|
|
// Send the request synchronously to retrieve the response. |
|
284
|
|
|
// Request and response log performed only if configured via `initLogger()` |
|
285
|
|
|
$request = new Request($method, $uri, $headers, $body); |
|
286
|
|
|
$this->logRequest($request); |
|
287
|
|
|
$this->response = $this->jsonApiClient->sendRequest($request); |
|
288
|
|
|
$this->logResponse($this->response); |
|
289
|
|
|
if ($this->getStatusCode() >= 400) { |
|
290
|
|
|
// Something bad just happened. |
|
291
|
|
|
$response = $this->getResponseBody(); |
|
292
|
|
|
// Message will be 'error` array, if absent use status massage |
|
293
|
|
|
$message = empty($response['error']) ? $this->getStatusMessage() : $response['error']; |
|
294
|
|
|
throw new BEditaClientException($message, $this->getStatusCode()); |
|
295
|
|
|
} |
|
296
|
|
|
|
|
297
|
|
|
return $this->response; |
|
298
|
|
|
} |
|
299
|
|
|
|
|
300
|
|
|
/** |
|
301
|
|
|
* Create request URI from path. |
|
302
|
|
|
* If path is absolute, i.e. it starts with 'http://' or 'https://', path is unchanged. |
|
303
|
|
|
* Otherwise `$this->apiBaseUrl` is prefixed, prepending a `/` if necessary. |
|
304
|
|
|
* |
|
305
|
|
|
* @param string $path Endpoint URL path (with or without starting `/`) or absolute API path |
|
306
|
|
|
* @param array|null $query Query string parameters. |
|
307
|
|
|
* @return Uri |
|
308
|
|
|
*/ |
|
309
|
|
|
protected function requestUri(string $path, ?array $query = null): Uri |
|
310
|
|
|
{ |
|
311
|
|
|
if (strpos($path, 'https://') !== 0 && strpos($path, 'http://') !== 0) { |
|
312
|
|
|
if (substr($path, 0, 1) !== '/') { |
|
313
|
|
|
$path = '/' . $path; |
|
314
|
|
|
} |
|
315
|
|
|
$path = $this->apiBaseUrl . $path; |
|
316
|
|
|
} |
|
317
|
|
|
$uri = new Uri($path); |
|
318
|
|
|
|
|
319
|
|
|
// if path contains query strings, remove them from path and add them to query filter |
|
320
|
|
|
parse_str($uri->getQuery(), $uriQuery); |
|
321
|
|
|
if ($query) { |
|
322
|
|
|
$query = array_merge((array)$uriQuery, (array)$query); |
|
323
|
|
|
$uri = $uri->withQuery(http_build_query($query)); |
|
324
|
|
|
} |
|
325
|
|
|
|
|
326
|
|
|
return $uri; |
|
327
|
|
|
} |
|
328
|
|
|
|
|
329
|
|
|
/** |
|
330
|
|
|
* Unset Authorization from defaultHeaders. |
|
331
|
|
|
* |
|
332
|
|
|
* @return void |
|
333
|
|
|
*/ |
|
334
|
|
|
protected function unsetAuthorization(): void |
|
335
|
|
|
{ |
|
336
|
|
|
if (!array_key_exists('Authorization', $this->defaultHeaders)) { |
|
337
|
|
|
return; |
|
338
|
|
|
} |
|
339
|
|
|
unset($this->defaultHeaders['Authorization']); |
|
340
|
|
|
} |
|
341
|
|
|
} |
|
342
|
|
|
|