-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathApiBaseCommand.php
More file actions
525 lines (472 loc) · 18.3 KB
/
ApiBaseCommand.php
File metadata and controls
525 lines (472 loc) · 18.3 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
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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<?php
declare(strict_types=1);
namespace Acquia\Cli\Command\Api;
use Acquia\Cli\Attribute\RequireAuth;
use Acquia\Cli\Command\CommandBase;
use Acquia\Cli\Exception\AcquiaCliException;
use AcquiaCloudApi\Connector\Client;
use AcquiaCloudApi\Exception\ApiErrorException;
use Closure;
use GuzzleHttp\Psr7\Utils;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\Question;
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Constraints\Type;
use Symfony\Component\Validator\Exception\ValidatorException;
use Symfony\Component\Validator\Validation;
#[RequireAuth]
#[AsCommand(name: 'api:base', hidden: true)]
class ApiBaseCommand extends CommandBase
{
protected string $method;
/**
* @var array<mixed>
*/
protected array $responses;
/**
* @var array<mixed>
*/
protected array $servers;
protected string $path;
/**
* @var array<mixed>
*/
private array $queryParams = [];
/**
* @var array<mixed>
*/
private array $postParams = [];
/**
* @var array<mixed>
*/
private array $pathParams = [];
protected function interact(InputInterface $input, OutputInterface $output): void
{
$params = array_merge($this->queryParams, $this->postParams, $this->pathParams);
foreach ($this->getDefinition()->getArguments() as $argument) {
if ($argument->isRequired() && !$input->getArgument($argument->getName())) {
$this->io->note([
"{$argument->getName()} is a required argument.",
$argument->getDescription(),
]);
// Choice question.
if (
array_key_exists($argument->getName(), $params)
&& array_key_exists('schema', $params[$argument->getName()])
&& array_key_exists('enum', $params[$argument->getName()]['schema'])
) {
$choices = $params[$argument->getName()]['schema']['enum'];
$answer = $this->io->choice("Select a value for {$argument->getName()}", $choices, $argument->getDefault());
} elseif (
array_key_exists($argument->getName(), $params)
&& array_key_exists('type', $params[$argument->getName()])
&& $params[$argument->getName()]['type'] === 'boolean'
) {
$answer = $this->io->choice("Select a value for {$argument->getName()}", [
'false',
'true',
], $argument->getDefault());
$answer = $answer === 'true';
} else {
// Free form.
$answer = $this->askFreeFormQuestion($argument, $params);
}
$input->setArgument($argument->getName(), $answer);
}
}
parent::interact($input, $output);
}
/**
* @throws \Acquia\Cli\Exception\AcquiaCliException
* @throws \JsonException
* @throws \AcquiaCloudApi\Exception\ApiErrorException
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
if ($this->getName() === 'api:base') {
throw new AcquiaCliException('api:base is not a valid command');
}
// Build query from non-null options.
$acquiaCloudClient = $this->cloudApiClientService->getClient();
$this->addQueryParamsToClient($input, $acquiaCloudClient);
$this->addPostParamsToClient($input, $acquiaCloudClient);
// Acquia PHP SDK cannot set the Accept header itself because it would break
// API calls returning octet streams (e.g., db backups). It's safe to use
// here because the API command should always return JSON.
$acquiaCloudClient->addOption('headers', [
'Accept' => 'application/hal+json, version=2',
]);
try {
if ($this->output->isVeryVerbose()) {
$acquiaCloudClient->addOption('debug', $this->output);
}
$path = $this->getRequestPath($input);
$response = $acquiaCloudClient->request($this->method, $path);
$exitCode = 0;
} catch (ApiErrorException $exception) {
if ($input->isInteractive()) {
throw $exception;
}
$response = $exception->getResponseBody();
$exitCode = 1;
}
if (substr($this->path, 0, 12) === '/translation' || $this->isMeoCommand()) {
$this->mungeResponse($response);
}
if ($exitCode || !$this->getParamFromInput($input, 'task-wait')) {
$contents = json_encode($response, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT);
$this->output->writeln($contents);
return $exitCode;
}
$notificationUuid = CommandBase::getNotificationUuidFromResponse($response);
$success = $this->waitForNotificationToComplete($this->cloudApiClientService->getClient(), $notificationUuid, "Waiting for task $notificationUuid to complete");
return $success ? Command::SUCCESS : Command::FAILURE;
}
private function mungeResponse(mixed &$response): void
{
if (is_object($response) && property_exists($response, '_links')) {
unset($response->_links);
}
foreach ($response as &$value) {
if (is_object($value) && property_exists($value, '_links')) {
unset($value->_links);
} elseif (is_array($value) && array_key_exists('_links', $value)) {
unset($value['_links']);
}
}
}
public function setMethod(string $method): void
{
$this->method = $method;
}
public function setResponses(array $responses): void
{
$this->responses = $responses;
}
public function setServers(array $servers): void
{
$this->servers = $servers;
}
public function setPath(string $path): void
{
$this->path = $path;
}
protected function getRequestPath(InputInterface $input): string
{
$path = $this->path;
$arguments = $input->getArguments();
// The command itself is the first argument. Remove it.
array_shift($arguments);
foreach ($arguments as $key => $value) {
$token = '{' . $key . '}';
if (str_contains($path, $token)) {
$path = str_replace($token, $value, $path);
}
}
return $path;
}
public function getMethod(): string
{
return $this->method;
}
public function addPostParameter(string $paramName, mixed $value): void
{
$this->postParams[$paramName] = $value;
}
public function addQueryParameter(string $paramName, mixed $value): void
{
$this->queryParams[$paramName] = $value;
}
public function getPath(): string
{
return $this->path;
}
public function addPathParameter(string $paramName, mixed $value): void
{
$this->pathParams[$paramName] = $value;
}
private function getParamFromInput(InputInterface $input, string $paramName): array|bool|string|int|null
{
if ($input->hasArgument($paramName)) {
return $input->getArgument($paramName);
}
if ($input->hasParameterOption('--' . $paramName)) {
return $input->getOption($paramName);
}
return null;
}
private function castParamType(array $paramSpec, array|string|bool|int $value): array|bool|int|string|object
{
$oneOf = $this->getParamTypeOneOf($paramSpec);
if (isset($oneOf)) {
$types = [];
foreach ($oneOf as $type) {
if ($type['type'] === 'array' && str_contains($value, ',')) {
return $this->castParamToArray($type, $value);
}
$types[] = $type['type'];
}
if (in_array('integer', $types, true) && ctype_digit($value)) {
return $this->doCastParamType('integer', $value);
}
} elseif ($this->getParamType($paramSpec) === 'array') {
if (is_array($value) && count($value) === 1) {
return $this->castParamToArray($paramSpec, $value[0]);
}
return $this->castParamToArray($paramSpec, $value);
}
$type = $this->getParamType($paramSpec);
if (!$type) {
return $value;
}
return $this->doCastParamType($type, $value);
}
private function doCastParamType(string $type, mixed $value): array|bool|int|string|object
{
return match ($type) {
'integer' => (int) $value,
'boolean' => $this->castBool($value),
'array' => $this->parseArrayValue($value),
'string' => (string) $value,
'object' => $this->castObject($value),
};
}
/**
* Parse a value into an array, handling JSON arrays and comma-separated values.
*
* @return array<mixed>
*/
private function parseArrayValue(mixed $value): array
{
if (!is_string($value)) {
return (array) $value;
}
$trimmed = trim($value);
if ($trimmed !== '' && in_array($trimmed[0], ['[', '{'], true)) {
$decoded = json_decode($trimmed, true);
if (is_array($decoded)) {
return $decoded;
}
}
return explode(',', $value);
}
private function castObject(mixed $value): object|string
{
if (is_array($value)) {
return (object)$value;
}
try {
return json_decode($value, false, 512, JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return $value;
}
}
public function castBool(mixed $val): bool
{
return (bool) (is_string($val) ? filter_var($val, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) : $val);
}
private function getParamType(array $paramSpec): ?string
{
// @todo File a CXAPI ticket regarding the inconsistent nesting of the 'type' property.
if (array_key_exists('type', $paramSpec)) {
return $paramSpec['type'];
}
if (array_key_exists('schema', $paramSpec) && array_key_exists('type', $paramSpec['schema'])) {
return $paramSpec['schema']['type'];
}
return null;
}
private function createCallableValidator(InputArgument $argument, array $params): ?callable
{
$validator = null;
if (array_key_exists($argument->getName(), $params)) {
$paramSpec = $params[$argument->getName()];
$constraints = [
new NotBlank(),
];
if ($type = $this->getParamType($paramSpec)) {
if (in_array($type, ['int', 'integer'])) {
// Need to evaluate whether a string contains only digits.
$constraints[] = new Type('digit');
} elseif ($type === 'array') {
$constraints[] = new Type('string');
} else {
$constraints[] = new Type($type);
}
}
if (array_key_exists('schema', $paramSpec)) {
$schema = $paramSpec['schema'];
$constraints = $this->createLengthConstraint($schema, $constraints);
$constraints = $this->createRegexConstraint($schema, $constraints);
}
$validator = $this->createValidatorFromConstraints($constraints);
}
return $validator;
}
/**
* @return array<mixed>
*/
private function createLengthConstraint(array $schema, array $constraints): array
{
if (array_key_exists('minLength', $schema) || array_key_exists('maxLength', $schema)) {
$lengthOptions = [];
if (array_key_exists('minLength', $schema)) {
$lengthOptions['min'] = $schema['minLength'];
}
if (array_key_exists('maxLength', $schema)) {
$lengthOptions['max'] = $schema['maxLength'];
}
$constraints[] = new Length($lengthOptions);
}
return $constraints;
}
/**
* @return array<mixed>
*/
protected function createRegexConstraint(array $schema, array $constraints): array
{
if (array_key_exists('format', $schema)) {
if ($schema['format'] === 'uuid') {
$constraints[] = CommandBase::getUuidRegexConstraint();
}
} elseif (array_key_exists('pattern', $schema)) {
$constraints[] = new Regex([
'message' => 'It must match the pattern ' . $schema['pattern'],
'pattern' => '/' . $schema['pattern'] . '/',
]);
}
return $constraints;
}
private function createValidatorFromConstraints(array $constraints): Closure
{
return static function (mixed $value) use ($constraints) {
$violations = Validation::createValidator()
->validate($value, $constraints);
if (count($violations)) {
throw new ValidatorException($violations->get(0)->getMessage());
}
return $value;
};
}
protected function addQueryParamsToClient(InputInterface $input, Client $acquiaCloudClient): void
{
if ($this->queryParams) {
foreach ($this->queryParams as $key => $paramSpec) {
// We may have a queryParam that is used in the path rather than the query string.
if ($input->hasOption($key) && $input->getOption($key) !== null) {
$acquiaCloudClient->addQuery($key, $input->getOption($key));
} elseif ($input->hasArgument($key) && $input->getArgument($key) !== null) {
$acquiaCloudClient->addQuery($key, $input->getArgument($key));
}
}
}
}
private function addPostParamsToClient(InputInterface $input, Client $acquiaCloudClient): void
{
if ($this->postParams) {
foreach ($this->postParams as $paramName => $paramSpec) {
$paramValue = $this->getParamFromInput($input, $paramName);
if (!is_null($paramValue)) {
$this->addPostParamToClient($paramName, $paramSpec, $paramValue, $acquiaCloudClient);
}
}
}
}
/**
* @param array|null $paramSpec
*/
private function addPostParamToClient(string $paramName, ?array $paramSpec, mixed $paramValue, Client $acquiaCloudClient): void
{
$paramName = ApiCommandHelper::restoreRenamedParameter($paramName);
if ($paramSpec) {
$paramValue = $this->castParamType($paramSpec, $paramValue);
}
if ($paramSpec && array_key_exists('format', $paramSpec) && $paramSpec["format"] === 'binary') {
$acquiaCloudClient->addOption('multipart', [
[
'contents' => Utils::tryFopen($paramValue, 'r'),
'name' => $paramName,
],
]);
} else {
$acquiaCloudClient->addOption('json', [$paramName => $paramValue]);
}
}
private function askFreeFormQuestion(InputArgument $argument, array $params): mixed
{
// Default value may be an empty array, which causes Question to choke.
$default = $argument->getDefault() ?: null;
$question = new Question("Enter a value for {$argument->getName()}", $default);
switch ($argument->getName()) {
case 'applicationUuid':
// @todo Provide a list of application UUIDs.
$question->setValidator(function (mixed $value) {
return $this->validateApplicationUuid($value);
});
break;
case 'environmentId':
// @todo Provide a list of environment IDs.
case 'source':
$question->setValidator(function (mixed $value) use ($argument): string {
return $this->validateEnvironmentUuid($value, $argument->getName());
});
break;
default:
$validator = $this->createCallableValidator($argument, $params);
$question->setValidator($validator);
break;
}
// Allow unlimited attempts.
$question->setMaxAttempts(null);
return $this->io->askQuestion($question);
}
/**
* @return null|array<mixed>
*/
private function getParamTypeOneOf(array $paramSpec): ?array
{
$oneOf = $paramSpec['oneOf'] ?? null;
if (array_key_exists('schema', $paramSpec) && array_key_exists('oneOf', $paramSpec['schema'])) {
$oneOf = $paramSpec['schema']['oneOf'];
}
return $oneOf;
}
private function castParamToArray(array $paramSpec, array|string $originalValue): string|array|bool|int
{
if (array_key_exists('items', $paramSpec) && array_key_exists('type', $paramSpec['items'])) {
if (!is_array($originalValue)) {
$originalValue = $this->doCastParamType('array', $originalValue);
}
$itemType = $paramSpec['items']['type'];
$array = [];
foreach ($originalValue as $key => $v) {
$array[$key] = $this->doCastParamType($itemType, $v);
}
return $array;
}
return $this->doCastParamType('array', $originalValue);
}
/**
* Check if this command is one of the MEO commands that should have _links removed.
*/
private function isMeoCommand(): bool
{
$commandName = $this->getName();
$meoCommands = [
'api:codebases:sites-list',
'api:environments:sites-list',
'api:site-instances:find',
'api:site-instances:database',
'api:site-instances:database:backups',
'api:site-instances:domains',
'api:site-instances:domain:add',
];
return in_array($commandName, $meoCommands, true);
}
}