-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathBaseApiClient.php
More file actions
435 lines (399 loc) · 13.4 KB
/
BaseApiClient.php
File metadata and controls
435 lines (399 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
<?php
/**
* This file is part of the Cloudinary PHP package.
*
* (c) Cloudinary
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Cloudinary\Api;
use Cloudinary\Api\Exception\AlreadyExists;
use Cloudinary\Api\Exception\ApiError;
use Cloudinary\Api\Exception\AuthorizationRequired;
use Cloudinary\Api\Exception\BadRequest;
use Cloudinary\Api\Exception\GeneralError;
use Cloudinary\Api\Exception\NotAllowed;
use Cloudinary\Api\Exception\NotFound;
use Cloudinary\Api\Exception\RateLimited;
use Cloudinary\ArrayUtils;
use Cloudinary\Cloudinary;
use Cloudinary\Configuration\ApiConfig;
use Cloudinary\JsonUtils;
use Cloudinary\Log\LoggerTrait;
use Cloudinary\StringUtils;
use Cloudinary\Utils;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Promise\Create;
use GuzzleHttp\Promise\PromiseInterface;
use InvalidArgumentException;
use JsonSerializable;
use Psr\Http\Message\ResponseInterface;
/**
* Class BaseApiClient
*
* @package Cloudinary\Api
*/
class BaseApiClient
{
use LoggerTrait;
/**
* @var array Cloudinary API Error Classes mapping between http error codes and Cloudinary exceptions
*/
protected const CLOUDINARY_API_ERROR_CLASSES
= [
HttpStatusCode::BAD_REQUEST => BadRequest::class,
HttpStatusCode::UNAUTHORIZED => AuthorizationRequired::class,
HttpStatusCode::FORBIDDEN => NotAllowed::class,
HttpStatusCode::NOT_FOUND => NotFound::class,
HttpStatusCode::CONFLICT => AlreadyExists::class,
HttpStatusCode::ENHANCE_YOUR_CALM => RateLimited::class,
HttpStatusCode::TOO_MANY_REQUESTS => RateLimited::class,
HttpStatusCode::INTERNAL_SERVER_ERROR => GeneralError::class,
];
/**
* @var Client The Http client instance. Performs actual network calls.
*/
public Client $httpClient;
/**
* @var ApiConfig $api The API configuration.
*/
protected ApiConfig $api;
/**
* @var string Base API URI. Stored here to allow sharing it publicly (for example upload form tag)
*/
protected string $baseUri;
/**
* Contains information about SDK user agent. Passed to the Cloudinary servers.
*
* Initialized on the first call to {@see self::userAgent()}
*
* Sample value: CloudinaryPHP/2.3.4 (PHP 5.6.7)
*
* @internal
*
* Do not change this value
*/
private static string $userAgent = 'CloudinaryPHP/' . Cloudinary::VERSION . ' (PHP ' . PHP_VERSION . ')';
/**
* Additional information to be passed with the USER_AGENT, e.g. 'CloudinaryMagento/1.0.1'.
* This value is set in platform-specific
* implementations that use cloudinary_php.
*
* The format of the value should be <ProductName>/Version[ (comment)].
*
* @see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
*
* @internal
*
* <b>Do not set this value in application code!</b>
*
* @var string
*/
public static string $userPlatform = '';
/**
* Gets base API url.
*
*
* @internal
*/
public function getBaseUri(): string
{
return $this->baseUri;
}
/**
* Performs an HTTP GET request with the given query parameters asynchronously.
*
* @param array|string $endPoint The API endpoint path.
* @param array $queryParams Query parameters
*
*
* @internal
*/
public function getAsync(array|string $endPoint, array $queryParams = []): PromiseInterface
{
return $this->callAsync(HttpMethod::GET, $endPoint, ['query' => Utils::buildHttpQuery($queryParams)]);
}
/**
* Performs an HTTP GET request with the given query parameters.
*
* @param array|string $endPoint The API endpoint path.
* @param array $queryParams Query parameters.
*
*
* @internal
*/
public function get(array|string $endPoint, array $queryParams = []): ApiResponse
{
return $this->getAsync($endPoint, $queryParams)->wait();
}
/**
* Performs an HTTP POST request with the given JSON object.
*
* @param array|string $endPoint The API endpoint path.
*
*
* @internal
*/
public function postJson(array|string $endPoint, array|JsonSerializable $parameters = []): ApiResponse
{
return $this->postJsonAsync($endPoint, $parameters)->wait();
}
/**
* Performs an HTTP POST request with the given JSON object asynchronously.
*
* @param array|string $endPoint The API endpoint path.
* @param array|JsonSerializable $json The json object
*
*
* @internal
*
*/
public function postJsonAsync(array|string $endPoint, array|JsonSerializable $json): PromiseInterface
{
return $this->callAsync(HttpMethod::POST, $endPoint, ['json' => $json]);
}
/**
* Performs an HTTP DELETE request with the given params
*
* @param array|string $endPoint The API endpoint path.
* @param array $fields Fields to send
*
*
*
* @internal
*/
public function delete(array|string $endPoint, array $fields = []): ApiResponse
{
return $this->callAsync(HttpMethod::DELETE, $endPoint, ['form_params' => $fields])->wait();
}
/**
* Performs an HTTP DELETE request with the given params.
*
* @param array|string $endPoint The API endpoint path.
* @param array|JsonSerializable $json JSON data.
*
*
* @internal
*/
public function deleteJson(array|string $endPoint, array|JsonSerializable $json = []): ApiResponse
{
return $this->callAsync(HttpMethod::DELETE, $endPoint, ['json' => $json])->wait();
}
/**
* Performs an HTTP POST request with the given parameters.
*
* @param array|string $endPoint The API endpoint path.
*
*
* @internal
*/
public function post(array|string $endPoint, array $parameters = []): ApiResponse
{
return $this->postAsync($endPoint, $parameters)->wait();
}
/**
* Performs an HTTP POST request with the given parameters asynchronously.
*
* @param array|string $endPoint The API endpoint path.
*
*
* @internal
*/
public function postAsync(array|string $endPoint, array $options = []): PromiseInterface
{
return $this->callAsync(HttpMethod::POST, $endPoint, $options);
}
/**
* Performs an HTTP PUT request with the given form params
*
* @param array|string $endPoint The API endpoint path.
* @param array $fields Fields to send.
*
*
*
* @internal
*/
public function put(array|string $endPoint, array $fields): ApiResponse
{
return $this->callAsync(HttpMethod::PUT, $endPoint, ['form_params' => $fields])->wait();
}
/**
* Performs an HTTP PUT request with the given form params.
*
* @param array|string $endPoint The API endpoint path.
* @param array|JsonSerializable $json JSON data.
*
*/
public function putJson(array|string $endPoint, array|JsonSerializable $json): ApiResponse
{
return $this->callAsync(HttpMethod::PUT, $endPoint, ['json' => $json])->wait();
}
/**
* Gets the API version string from the version.
*
* @param string $apiVersion The API version in the form Major.minor (for example: 1.1).
*
* @return string API version string
*
* @internal
*/
public static function apiVersion(string $apiVersion = ApiConfig::DEFAULT_API_VERSION): string
{
return 'v' . str_replace('.', '_', $apiVersion);
}
/**
* Internal helper method for converting array of URL path parts to string
*
* @param array|string $endPoint The API endpoint path.
*
* @return array|string resulting URL path
*
* @internal
*/
protected static function finalizeEndPoint(array|string $endPoint): array|string
{
if (is_array($endPoint)) {
$endPoint = ArrayUtils::implodeUrl($endPoint);
}
return $endPoint;
}
/**
* Performs an HTTP call asynchronously
*
* @param string $method HTTP method
* @param array|string $endPoint The API endpoint path.
* @param array $options Array containing request body and additional options passed to the HTTP Client
*
*
* @internal
*/
protected function callAsync(string $method, array|string $endPoint, array $options): PromiseInterface
{
$endPoint = self::finalizeEndPoint($endPoint);
$options['headers'] = ArrayUtils::mergeNonEmpty(
ArrayUtils::get($options, 'headers', []),
ArrayUtils::get($options, 'extra_headers', [])
);
$this->getLogger()->debug("Making async $method request", ['method' => $method, 'endPoint' => $endPoint]);
return $this
->httpClient
->requestAsync($method, $endPoint, $options)
->then(
function (ResponseInterface $response) {
$this->getLogger()->debug(
'Response received for async request',
['statusCode' => $response->getStatusCode()]
);
try {
return Create::promiseFor($this->handleApiResponse($response));
} catch (Exception $e) {
$this->getLogger()->critical(
'Async request failed',
[
'code' => $e->getCode(),
'message' => $e->getMessage(),
]
);
return Create::rejectionFor($e);
}
},
function (Exception $error) {
$this->getLogger()->critical(
'Async request failed',
[
'code' => $error->getCode(),
'message' => $error->getMessage(),
]
);
if ($error instanceof ClientException) {
return Create::rejectionFor($this->handleApiResponse($error->getResponse()));
}
return Create::rejectionFor($error);
}
);
}
/**
* Provides the {@see ApiClient::$userAgent} string that is passed to the Cloudinary servers.
*
* Prepends {@see ApiClient::$userPlatform} if it is defined.
*
*
* @internal
*/
protected static function userAgent(): string
{
if (empty(self::$userPlatform)) {
return self::$userAgent;
}
return self::$userPlatform . ' ' . self::$userAgent;
}
/**
* Handles HTTP response from Cloudinary API.
*
* @param ResponseInterface $response Response from HTTP request to the Cloudinary server
*
*
* @throws ApiError
*
* @internal
*/
private function handleApiResponse(ResponseInterface $response): ApiResponse
{
$statusCode = $response->getStatusCode();
if ($statusCode !== HttpStatusCode::OK) {
if (array_key_exists($statusCode, self::CLOUDINARY_API_ERROR_CLASSES)) {
$errorClass = self::CLOUDINARY_API_ERROR_CLASSES[$statusCode];
$responseJson = $this->parseJsonResponse($response);
$message = ArrayUtils::get(
$responseJson['error']['message'],
'message',
$responseJson['error']['message']
);
$this->getLogger()->critical(
'Request to Cloudinary server returned an error',
[
'statusCode' => $statusCode,
'message' => $message,
]
);
throw new $errorClass($message);
}
$message = "Server returned unexpected status code - {$response->getStatusCode()} - " .
StringUtils::truncateMiddle($response->getBody());
$this->getLogger()->critical($message);
throw new GeneralError($message);
}
$responseJson = $this->parseJsonResponse($response);
$responseHeaders = $response->getHeaders();
return new ApiResponse($responseJson, $responseHeaders);
}
/**
* Parses JSON body (if possible)
*
* @param ResponseInterface $response Response from HTTP request to Cloudinary server
*
*
* @throws GeneralError
*
* @internal
*/
private function parseJsonResponse(ResponseInterface $response): mixed
{
try {
$responseJson = JsonUtils::decode($response->getBody());
} catch (InvalidArgumentException $iae) {
$message = sprintf(
'Error parsing server response (%s) - %s. Got - %s',
$response->getStatusCode(),
$response->getBody(),
$iae
);
$this->getLogger()->error($message);
throw new GeneralError($message);
}
return $responseJson;
}
}