/
ApiClient.php
471 lines (414 loc) · 14.5 KB
/
ApiClient.php
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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
<?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\ApiError;
use Cloudinary\Api\Exception\GeneralError;
use Cloudinary\ArrayUtils;
use Cloudinary\Configuration\ApiConfig;
use Cloudinary\Configuration\CloudConfig;
use Cloudinary\Configuration\Configuration;
use Cloudinary\FileUtils;
use Cloudinary\Utils;
use Exception;
use GuzzleHttp\Client;
use GuzzleHttp\Promise\Create;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\LimitStream;
use InvalidArgumentException;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UriInterface;
/**
* Class ApiClient
*
* @internal
*/
class ApiClient extends BaseApiClient
{
/**
* @var CloudConfig $cloud The cloud configuration.
*/
protected $cloud;
/**
* ApiClient constructor.
*
* @param $configuration
*/
public function __construct($configuration = null)
{
if ($configuration === null) {
$configuration = Configuration::instance(); // get global instance
}
$this->configuration($configuration);
$this->baseUri = "{$this->api->uploadPrefix}/" . self::apiVersion($this->api->apiVersion)
. "/{$this->cloud->cloudName}/";
$this->createHttpClient();
}
protected function createHttpClient()
{
$this->httpClient = new Client($this->buildHttpClientConfig());
}
/**
* Gets cloud configuration of the current client.
*
* @return CloudConfig
*
* @internal
*/
public function getCloud()
{
return $this->cloud;
}
/**
* Sets Configuration.
*
* @param mixed $configuration The configuration source.
*
* @return static
*
* @internal
*/
public function configuration($configuration)
{
$tempConfiguration = new Configuration($configuration); // TODO: improve performance here
$this->cloud = $tempConfiguration->cloud;
$this->api = $tempConfiguration->api;
$this->logging = $tempConfiguration->logging;
return $this;
}
/**
* Performs an HTTP POST request with the given form parameters.
*
* @param string|array $endPoint The API endpoint path.
* @param array $formParams The form parameters
*
* @return ApiResponse
*
* @internal
*/
public function postForm($endPoint, $formParams)
{
return $this->postFormAsync($endPoint, $formParams)->wait();
}
/**
* Performs an HTTP POST request with the given form parameters asynchronously.
*
* Please note that form parameters are encoded in a slightly different way, see Utils::buildHttpQuery for details.
*
* @param string|array $endPoint The API endpoint path.
* @param array $formParams The form parameters
*
* @return PromiseInterface
*
* @see Utils::buildHttpQuery
*
* @internal
*/
public function postFormAsync($endPoint, $formParams)
{
return $this->callAsync(HttpMethod::POST, $endPoint, ['body' => Utils::buildHttpQuery($formParams)]);
}
/**
* Signs posted parameters using configured cloud credentials and posts to the endpoint.
*
* @param string|array $endPoint The API endpoint path.
* @param array $formParams The form parameters
*
* @return PromiseInterface
*
* @internal
*/
public function postAndSignFormAsync($endPoint, $formParams)
{
if (! $this->cloud->oauthToken) {
ApiUtils::signRequest($formParams, $this->cloud);
}
return $this->postFormAsync($endPoint, $formParams);
}
/**
* Signs posted parameters using configured account credentials and posts as a JSON to the endpoint.
*
* @param string|array $endPoint The API endpoint path.
* @param array $params The parameters
*
* @return PromiseInterface
*
* @internal
*/
public function postAndSignJsonAsync($endPoint, $params)
{
ApiUtils::signRequest($params, $this->cloud);
return $this->postJsonAsync($endPoint, $params);
}
/**
* Helper method for posting multipart data asynchronously.
*
* @param string|array $endPoint The API endpoint path.
* @param $multiPart
* @param array $headers
* @param array $options Additional options for Http client
*
* @return PromiseInterface
*
* @internal
*/
public function postMultiPartAsync($endPoint, $multiPart, $headers = null, $options = [])
{
ArrayUtils::addNonEmpty($options, 'multipart', $multiPart);
ArrayUtils::addNonEmpty($options, 'headers', $headers);
return $this->postAsync(self::finalizeEndPoint($endPoint), $options);
}
/**
* Helper method for posting multipart data.
*
* @param string|array $endPoint The API endpoint path.
* @param $multiPart
* @param array $headers
* @param array $options Additional options for Http client
*
* @return ApiResponse
*
* @internal
*
*/
public function postMultiPart($endPoint, $multiPart, $headers = null, $options = [])
{
return $this->postMultiPartAsync($endPoint, $multiPart, $headers, $options)->wait();
}
/**
* Uploads a file to the Cloudinary server.
*
* @param string|array $endPoint The API endpoint path.
* @param mixed $file File to upload, can be a local path, URL, stream, etc.
* @param array $parameters Additional parameters to be sent in the body
* @param array $options Additional options, including options for the HTTP client
*
* @return ApiResponse
*
* @throws ApiError
*
* @internal
*/
public function postFile($endPoint, $file, $parameters, $options = [])
{
return $this->postFileAsync($endPoint, $file, $parameters, $options)->wait();
}
/**
* Uploads a file to the Cloudinary server asynchronously.
*
* @param string|array $endPoint The API endpoint path.
* @param mixed $file File to upload, can be a local path, URL, stream, etc.
* @param array $parameters Additional parameters to be sent in the body
* @param array $options Additional options, including options for the HTTP client
*
* @return PromiseInterface
*
* @throws ApiError
* @throws Exception
*
* @internal
*/
public function postFileAsync($endPoint, $file, $parameters, $options = [])
{
$unsigned = ArrayUtils::get($options, 'unsigned');
if (! $this->cloud->oauthToken && ! $unsigned) {
ApiUtils::signRequest($parameters, $this->cloud);
}
try {
$fileHandle = FileUtils::handleFile($file);
} catch (GeneralError $e) {
$this->getLogger()->critical(
'Error while attempting to upload a file',
[
'exception' => $e->getMessage(),
'class' => self::class,
'endPoint' => $endPoint,
'file' => $file,
'options' => $options,
]
);
throw $e;
}
if ($fileHandle instanceof UriInterface) {
return $this->postSingleChunkAsync($endPoint, $fileHandle, $parameters, $options);
}
if (empty(ArrayUtils::get($options, 'filename')) && FileUtils::isLocalFilePath($file)) {
$options['filename'] = basename($file); // set local file name
}
$size = $fileHandle->getSize();
$options[ApiConfig::CHUNK_SIZE] = ArrayUtils::get($options, ApiConfig::CHUNK_SIZE, $this->api->chunkSize);
$options[ApiConfig::TIMEOUT] = ArrayUtils::get($options, ApiConfig::TIMEOUT, $this->api->uploadTimeout);
/** @noinspection IsEmptyFunctionUsageInspection */
if (empty($size) || $size <= $options[ApiConfig::CHUNK_SIZE]) {
return $this->postSingleChunkAsync($endPoint, $fileHandle, $parameters, $options);
}
return $this->postLargeFileAsync($endPoint, $fileHandle, $parameters, $options);
}
/**
* Performs an HTTP call asynchronously.
*
* @param string $method An HTTP method.
* @param string|array $endPoint An API endpoint path.
* @param array $options An array containing request body and additional options passed to the HTTP Client.
*
* @return PromiseInterface
*
* @internal
*/
protected function callAsync($method, $endPoint, $options)
{
static::validateAuthorization($this->cloud, $options);
return parent::callAsync($method, $endPoint, $options);
}
/**
* Posts a large file in chunks asynchronously
*
* @param string|array $endPoint The API endpoint path.
* @param StreamInterface $fileHandle The file handle
* @param array $parameters Additional form parameters
* @param array $options Additional options
*
* @return PromiseInterface
* @throws Exception
*
* @internal
*/
private function postLargeFileAsync($endPoint, $fileHandle, $parameters, $options = [])
{
$this->getLogger()->debug('Making a Large File Async POST request');
$uploadResult = null;
$chunkSize = ArrayUtils::get($options, ApiConfig::CHUNK_SIZE, ApiConfig::DEFAULT_CHUNK_SIZE);
$fileSize = $fileHandle->getSize(); // Can be null as well
/** @noinspection IsEmptyFunctionUsageInspection */
$rangeHeaderTemplate = 'bytes %s-%s' . (! empty($fileSize) ? "/$fileSize" : '');
$options['headers'] = [
'X-Unique-Upload-Id' => Utils::randomPublicId($this->cloud->apiSecret),
];
if ($fileHandle->isSeekable()) {
$fileHandle->rewind();
}
while (! $fileHandle->eof()) {
$currPos = $fileHandle->tell();
$currChunk = new LimitStream($fileHandle, $chunkSize, $currPos);
$options['headers']['Content-Range'] = sprintf(
$rangeHeaderTemplate,
$currPos,
$currPos + $currChunk->getSize() - 1
);
try {
$this->getLogger()->debug('Making a Single Chunk Async POST request');
// TODO: use pool here or send requests in an async manner(?)
$uploadResult = $this->postSingleChunkAsync($endPoint, $currChunk, $parameters, $options)->wait();
} catch (Exception $e) { // TODO: retry (?)
$this->getLogger()->critical(
'Single Chunk Async POST request failed',
[
'code' => $e->getCode(),
'message' => $e->getMessage(),
]
);
return Create::rejectionFor($e);
}
ArrayUtils::addNonEmptyFromOther($parameters, 'public_id', $uploadResult);
}
return Create::promiseFor($uploadResult);
}
/**
* Posts a single chunk of the large file upload request asynchronously
*
* @param string|array $endPoint The API endpoint path.
* @param mixed $singleChunk The data of a single chunk of the file
* @param array $parameters Additional form parameters
* @param array $options Additional options
*
* @return PromiseInterface
*
* @internal
*
*/
protected function postSingleChunkAsync($endPoint, $singleChunk, $parameters, $options = [])
{
$filePart = [
'name' => ArrayUtils::get($options, 'file_field', 'file'),
'contents' => $singleChunk,
];
ArrayUtils::addNonEmptyFromOther($filePart, 'filename', $options);
$multiPart = self::buildMultiPart($parameters);
$multiPart [] = $filePart;
$headers = ArrayUtils::pop($options, 'headers');
return $this->postMultiPartAsync($endPoint, $multiPart, $headers, $options);
}
/**
* Build configuration used by HTTP client
*
* @return array
*
* @internal
*/
protected function buildHttpClientConfig()
{
$clientConfig = [
'base_uri' => $this->baseUri,
'connect_timeout' => $this->api->connectionTimeout,
'timeout' => $this->api->timeout,
'proxy' => $this->api->apiProxy,
'headers' => ['User-Agent' => self::userAgent()],
'http_errors' => false, // We handle HTTP errors by ourselves and throw corresponding exceptions
];
if (isset($this->cloud->oauthToken)) {
$authConfig = [
'headers' => ['Authorization' => 'Bearer ' . $this->cloud->oauthToken],
];
} else {
$authConfig = [
'auth' => [$this->cloud->apiKey, $this->cloud->apiSecret],
];
}
return array_merge_recursive($clientConfig, $authConfig);
}
/**
* Builds multipart request body from an array of parameters
*
* @param array $parameters The input parameters
*
* @return array
*
* @internal
*/
private static function buildMultiPart($parameters)
{
return array_values(
ArrayUtils::mapAssoc(
static function ($key, $value) {
return ['name' => $key, 'contents' => $value];
},
$parameters
)
);
}
/**
* Validates if all required authorization params are passed.
*
* @param CloudConfig $cloudConfig A config to validate.
* @param array $options An array containing request body and additional options passed to the HTTP
* Client.
*
* @throws InvalidArgumentException In a case not all required keys are set.
*
* @internal
*/
protected static function validateAuthorization($cloudConfig, $options)
{
$keysToValidate = ['cloudName'];
if (empty($cloudConfig->oauthToken)) {
array_push($keysToValidate, 'apiKey', 'apiSecret');
}
$cloudConfig->assertNotEmpty($keysToValidate);
}
}