-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathAbstractCommand.php
More file actions
1055 lines (900 loc) · 37.2 KB
/
AbstractCommand.php
File metadata and controls
1055 lines (900 loc) · 37.2 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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <[email protected]>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\CLI;
use CodeIgniter\CLI\Attributes\Command;
use CodeIgniter\CLI\Exceptions\ArgumentCountMismatchException;
use CodeIgniter\CLI\Exceptions\InvalidArgumentDefinitionException;
use CodeIgniter\CLI\Exceptions\InvalidOptionDefinitionException;
use CodeIgniter\CLI\Exceptions\OptionValueMismatchException;
use CodeIgniter\CLI\Exceptions\UnknownOptionException;
use CodeIgniter\CLI\Input\Argument;
use CodeIgniter\CLI\Input\Option;
use CodeIgniter\Exceptions\LogicException;
use CodeIgniter\HTTP\CLIRequest;
use Config\App;
use Config\Services;
use ReflectionClass;
use Throwable;
/**
* Base class for all modern spark commands.
*
* Each command should extend this class and implement the `execute()` method.
*/
abstract class AbstractCommand
{
private readonly string $name;
private readonly string $description;
private readonly string $group;
/**
* @var list<non-empty-string>
*/
private array $usages = [];
/**
* @var array<non-empty-string, Argument>
*/
private array $argumentsDefinition = [];
/**
* @var array<non-empty-string, Option>
*/
private array $optionsDefinition = [];
/**
* Map of shortcut character to the option name that declared it.
*
* @var array<non-empty-string, non-empty-string>
*/
private array $shortcuts = [];
/**
* Map of negated name to the option name it negates.
*
* @var array<non-empty-string, non-empty-string>
*/
private array $negations = [];
/**
* Cached list of required argument names, populated as definitions are added.
*
* @var list<non-empty-string>
*/
private array $requiredArguments = [];
/**
* Cache of resolved `Command` attributes keyed by class name.
*
* @var array<class-string<self>, Command>
*/
private static array $commandAttributeCache = [];
/**
* The unbound arguments that can be passed to other commands when called via the `call()` method.
*
* @var list<non-empty-string>
*/
private array $unboundArguments = [];
/**
* The unbound options that can be passed to child commands when called via the `call()` method.
*
* @var array<non-empty-string, list<string|null>|string|null>
*/
private array $unboundOptions = [];
/**
* The validated arguments after binding, which will be passed to the `execute()` method.
*
* @var array<non-empty-string, list<string>|string>
*/
private array $validatedArguments = [];
/**
* The validated options after binding, which will be passed to the `execute()` method.
*
* @var array<non-empty-string, bool|list<string>|string|null>
*/
private array $validatedOptions = [];
private ?string $lastOptionalArgument = null;
private ?string $lastArrayArgument = null;
/**
* Whether the command is in interactive mode. When `null`, the interactive state is resolved based
* on the presence of the `--no-interaction` option and whether STDIN is a TTY. If boolean, this value
* takes precedence over the flag and TTY detection.
*/
private ?bool $interactive = null;
/**
* @throws InvalidArgumentDefinitionException
* @throws InvalidOptionDefinitionException
* @throws LogicException
*/
public function __construct(private readonly Commands $commands)
{
$attribute = $this->getCommandAttribute();
$this->name = $attribute->name;
$this->description = $attribute->description;
$this->group = $attribute->group;
$this->configure();
$this->provideDefaultOptions();
$this->createDefaultUsage();
}
public function getCommandRunner(): Commands
{
return $this->commands;
}
public function getName(): string
{
return $this->name;
}
public function getDescription(): string
{
return $this->description;
}
public function getGroup(): string
{
return $this->group;
}
/**
* @return list<non-empty-string>
*/
public function getUsages(): array
{
return $this->usages;
}
/**
* @return array<non-empty-string, Argument>
*/
public function getArgumentsDefinition(): array
{
return $this->argumentsDefinition;
}
/**
* @return array<non-empty-string, Option>
*/
public function getOptionsDefinition(): array
{
return $this->optionsDefinition;
}
/**
* Returns the map of shortcut character to its owning option name.
*
* @return array<non-empty-string, non-empty-string>
*/
public function getShortcuts(): array
{
return $this->shortcuts;
}
/**
* Returns the map of negated name to the option name it negates.
*
* @return array<non-empty-string, non-empty-string>
*/
public function getNegations(): array
{
return $this->negations;
}
/**
* Appends a usage example aside from the default usage.
*
* @param non-empty-string $usage
*/
public function addUsage(string $usage): static
{
$this->usages[] = $usage;
return $this;
}
/**
* Adds an argument definition to the command.
*
* @throws InvalidArgumentDefinitionException
*/
public function addArgument(Argument $argument): static
{
$name = $argument->name;
if ($this->hasArgument($name)) {
throw new InvalidArgumentDefinitionException(lang('Commands.duplicateArgument', [$name]));
}
if ($this->lastArrayArgument !== null) {
throw new InvalidArgumentDefinitionException(lang('Commands.argumentAfterArrayArgument', [$name, $this->lastArrayArgument]));
}
if ($argument->required && $this->lastOptionalArgument !== null) {
throw new InvalidArgumentDefinitionException(lang('Commands.requiredArgumentAfterOptionalArgument', [$name, $this->lastOptionalArgument]));
}
if ($argument->isArray) {
$this->lastArrayArgument = $name;
}
if ($argument->required) {
$this->requiredArguments[] = $name;
} else {
$this->lastOptionalArgument = $name;
}
$this->argumentsDefinition[$name] = $argument;
return $this;
}
/**
* Adds an option definition to the command.
*
* @throws InvalidOptionDefinitionException
*/
public function addOption(Option $option): static
{
$name = $option->name;
if ($this->hasOption($name)) {
throw new InvalidOptionDefinitionException(lang('Commands.duplicateOption', [$name]));
}
if ($this->hasNegation($name)) {
throw new InvalidOptionDefinitionException(lang('Commands.optionClashesWithExistingNegation', [$name, $this->negations[$name]]));
}
if ($option->shortcut !== null && $this->hasShortcut($option->shortcut)) {
throw new InvalidOptionDefinitionException(lang('Commands.duplicateShortcut', [$option->shortcut, $name, $this->shortcuts[$option->shortcut]]));
}
if ($option->negation !== null && $this->hasOption($option->negation)) {
throw new InvalidOptionDefinitionException(lang('Commands.negatableOptionNegationExists', [$name]));
}
if ($option->shortcut !== null) {
$this->shortcuts[$option->shortcut] = $name;
}
if ($option->negation !== null) {
$this->negations[$option->negation] = $name;
}
$this->optionsDefinition[$name] = $option;
return $this;
}
/**
* Renders the given `Throwable`.
*
* This is usually not needed to be called directly as the `Throwable` will be automatically rendered by the framework when it is thrown,
* but it can be useful to call this method directly when you want to render a `Throwable` that is caught by the command itself.
*/
public function renderThrowable(Throwable $e): void
{
// The exception handler picks a renderer based on the shared request
// instance. Ensure it is a CLIRequest; if the current shared request is
// not, swap it temporarily and restore it afterwards so other code paths
// do not observe our mutation.
$previous = Services::get('request');
$swapped = false;
if (! $previous instanceof CLIRequest) {
Services::createRequest(config(App::class), true);
$swapped = true;
}
try {
service('exceptions')->exceptionHandler($e);
} finally {
if ($swapped) {
Services::override('request', $previous);
}
}
}
/**
* Checks if the command has an argument defined with the given name.
*/
public function hasArgument(string $name): bool
{
return array_key_exists($name, $this->argumentsDefinition);
}
/**
* Checks if the command has an option defined with the given name.
*/
public function hasOption(string $name): bool
{
return array_key_exists($name, $this->optionsDefinition);
}
/**
* Checks if the command has a shortcut defined with the given name.
*/
public function hasShortcut(string $shortcut): bool
{
return array_key_exists($shortcut, $this->shortcuts);
}
/**
* Checks if the command has a negation defined with the given name.
*/
public function hasNegation(string $name): bool
{
return array_key_exists($name, $this->negations);
}
/**
* Reports whether the command is currently in interactive mode.
*
* Resolution order:
* 1. An explicit `setInteractive()` call wins.
* 2. Otherwise, the command is interactive when STDIN is a TTY.
*
* Non-CLI contexts (e.g., a controller invoking `command()`) don't expose
* `STDIN` at all — those always resolve as non-interactive.
*
* Note: the `--no-interaction` / `-N` flag is folded into the explicit state
* by `run()` before interactive hooks fire, so callers do not need to
* inspect the options array themselves.
*/
public function isInteractive(): bool
{
if ($this->interactive !== null) {
return $this->interactive;
}
return defined('STDIN') && CLI::streamSupports('stream_isatty', \STDIN);
}
/**
* Pins the interactive state, overriding both the `--no-interaction` flag
* and STDIN TTY detection. Typically called from `initialize()` or by
* an outer caller that needs to force a specific mode.
*/
public function setInteractive(bool $interactive): static
{
$this->interactive = $interactive;
return $this;
}
/**
* Runs the command.
*
* The lifecycle is:
*
* 1. {@see initialize()} and {@see interact()} are handed the raw parsed
* input by reference, in that order. Both can mutate the tokens before
* the framework interprets them against the declared definitions.
* 2. The post-hook input is snapshotted into `$unboundArguments` and
* `$unboundOptions` so the unbound accessors can report the tokens
* carried into binding (as opposed to what defaults resolved to).
* Any mutations performed in `initialize()` or `interact()` are
* therefore reflected in the snapshot.
* 3. {@see bind()} maps the raw tokens onto the declared arguments and
* options, applying defaults and coercing flag/negation values.
* 4. {@see validate()} rejects the bound result if it violates any of the
* declarations — missing required argument, unknown option, value/flag
* mismatches, and so on.
* 5. The bound-and-validated values are snapshotted into
* `$validatedArguments` / `$validatedOptions` and then passed to
* {@see execute()}, whose integer return is the command's exit code.
*
* @param list<string> $arguments Parsed arguments from command line.
* @param array<string, list<string|null>|string|null> $options Parsed options from command line.
*
* @throws ArgumentCountMismatchException
* @throws LogicException
* @throws OptionValueMismatchException
* @throws UnknownOptionException
*/
final public function run(array $arguments, array $options): int
{
$this->initialize($arguments, $options);
if ($this->interactive === null && $this->hasUnboundOption('no-interaction', $options)) {
$this->interactive = false;
}
if ($this->isInteractive()) {
$this->interact($arguments, $options);
}
$this->unboundArguments = $arguments;
$this->unboundOptions = $options;
[$boundArguments, $boundOptions] = $this->bind($arguments, $options);
$this->validate($boundArguments, $boundOptions);
$this->validatedArguments = $boundArguments;
$this->validatedOptions = $boundOptions;
return $this->execute($boundArguments, $boundOptions);
}
/**
* Configures the command's arguments and options definitions.
*
* This method is called from the constructor of the command.
*
* @throws InvalidArgumentDefinitionException
* @throws InvalidOptionDefinitionException
*/
protected function configure(): void
{
}
/**
* Initializes a command before the arguments and options are bound to their definitions.
*
* This is especially useful for commands that calls another commands, and needs to adjust the
* arguments and options before calling the other command.
*
* @param list<string> $arguments Parsed arguments from command line.
* @param array<string, list<string>|string|null> $options Parsed options from command line.
*/
protected function initialize(array &$arguments, array &$options): void
{
}
/**
* Interacts with the user before executing the command. This should only be called if the command is being run
* in interactive mode, which is the default when running commands from the command line.
*
* This is especially useful for commands that needs to ask the user for confirmation before executing the command.
* It can also be used to ask the user for additional information that is not provided in the command line arguments and options.
*
* @param list<string> $arguments Parsed arguments from command line.
* @param array<string, list<string>|string|null> $options Parsed options from command line.
*/
protected function interact(array &$arguments, array &$options): void
{
}
/**
* Executes the command with the bound arguments and options.
*
* Validation of the bound arguments and options is done before this method is called.
* As such, this method should not throw any exceptions. All exceptions should be rendered
* with a non-zero exit code.
*
* @param array<string, list<string>|string> $arguments Bound arguments using the command's arguments definition.
* @param array<string, bool|list<string>|string|null> $options Bound options using the command's options definition.
*/
abstract protected function execute(array $arguments, array $options): int;
/**
* Calls another command from the current command.
*
* @param list<string> $arguments Parsed arguments from command line.
* @param array<string, list<string>|string|null> $options Parsed options from command line.
* @param bool|null $noInteractionOverride `null` (default) propagates the parent's non-interactive state;
* `true` forces the sub-command non-interactive by injecting
* `--no-interaction`; `false` strips any inherited
* `--no-interaction` so the sub-command resolves its own state
* (TTY detection may still downgrade it).
*/
protected function call(string $command, array $arguments = [], array $options = [], ?bool $noInteractionOverride = null): int
{
return $this->commands->runCommand($command, $arguments, $this->resolveChildInteractiveState($options, $noInteractionOverride));
}
/**
* Gets the unbound arguments that can be passed to other commands when called via the `call()` method.
*
* @return list<string>
*/
protected function getUnboundArguments(): array
{
return $this->unboundArguments;
}
/**
* Gets the unbound argument at the given index.
*
* @throws LogicException
*/
protected function getUnboundArgument(int $index): string
{
if (! array_key_exists($index, $this->unboundArguments)) {
throw new LogicException(sprintf('Unbound argument at index "%d" does not exist.', $index));
}
return $this->unboundArguments[$index];
}
/**
* Gets the unbound options that can be passed to other commands when called via the `call()` method.
*
* @return array<string, list<string|null>|string|null>
*/
protected function getUnboundOptions(): array
{
return $this->unboundOptions;
}
/**
* Reads the raw (unbound) value of the option with the given declared name,
* resolving through its shortcut and negation. Returns `null` when the
* option was not provided under any of those aliases.
*
* Inside {@see interact()}, pass the `$options` parameter explicitly because
* the instance state is not yet populated at that point. Elsewhere, omit
* `$options` to read from the instance state.
*
* @param array<string, list<string|null>|string|null>|null $options
*
* @return list<string|null>|string|null
*
* @throws LogicException
*/
protected function getUnboundOption(string $name, ?array $options = null): array|string|null
{
$this->assertOptionIsDefined($name);
$options ??= $this->unboundOptions;
if (array_key_exists($name, $options)) {
return $options[$name];
}
$definition = $this->optionsDefinition[$name];
if ($definition->shortcut !== null && array_key_exists($definition->shortcut, $options)) {
return $options[$definition->shortcut];
}
if ($definition->negation !== null && array_key_exists($definition->negation, $options)) {
return $options[$definition->negation];
}
return null;
}
/**
* Returns whether the option with the given declared name was provided in
* the raw (unbound) input — under its long name, shortcut, or negation.
*
* Inside {@see interact()}, pass the `$options` parameter explicitly; elsewhere
* omit it to read from instance state.
*
* @param array<string, list<string|null>|string|null>|null $options
*
* @throws LogicException
*/
protected function hasUnboundOption(string $name, ?array $options = null): bool
{
$this->assertOptionIsDefined($name);
$options ??= $this->unboundOptions;
if (array_key_exists($name, $options)) {
return true;
}
$definition = $this->optionsDefinition[$name];
if ($definition->shortcut !== null && array_key_exists($definition->shortcut, $options)) {
return true;
}
return $definition->negation !== null && array_key_exists($definition->negation, $options);
}
/**
* Gets the validated arguments after binding and validation.
*
* @return array<string, list<string>|string>
*/
protected function getValidatedArguments(): array
{
return $this->validatedArguments;
}
/**
* Gets the validated argument with the given name.
*
* @return list<string>|string
*
* @throws LogicException
*/
protected function getValidatedArgument(string $name): array|string
{
if (! array_key_exists($name, $this->validatedArguments)) {
throw new LogicException(sprintf('Validated argument with name "%s" does not exist.', $name));
}
return $this->validatedArguments[$name];
}
/**
* Gets the validated options after binding and validation.
*
* @return array<string, bool|list<string>|string|null>
*/
protected function getValidatedOptions(): array
{
return $this->validatedOptions;
}
/**
* Gets the validated option with the given name.
*
* @return bool|list<string>|string|null
*
* @throws LogicException
*/
protected function getValidatedOption(string $name): array|bool|string|null
{
if (! array_key_exists($name, $this->validatedOptions)) {
throw new LogicException(sprintf('Validated option with name "%s" does not exist.', $name));
}
return $this->validatedOptions[$name];
}
/**
* Registers the options that the framework injects into every modern
* command. Every option registered here is load-bearing:
*
* - `--help` / `-h`: `Console` detects it and routes to the `help` command.
* - `--no-header`: `Console` strips it before rendering the banner.
* - `--no-interaction` / `-N`: `run()` folds it into the interactive state
* and `resolveChildInteractiveState()` reads it to drive the `call()` cascade.
*
* Subclasses that override this hook should re-register these options or
* accept that the corresponding framework features will be broken for
* the subclass.
*/
protected function provideDefaultOptions(): void
{
$this
->addOption(new Option(name: 'help', shortcut: 'h', description: 'Display help for the given command.'))
->addOption(new Option(name: 'no-header', description: 'Do not display the banner when running the command.'))
->addOption(new Option(name: 'no-interaction', shortcut: 'N', description: 'Do not ask any interactive questions.'));
}
/**
* Reconciles the caller's explicit intent (`$noInteractionOverride`) with
* the parent command's own interactive state to produce the `$options`
* that `call()` should hand to the sub-command.
*
* - `null` (default) propagates the parent's non-interactive state by
* adding `--no-interaction` when the parent itself is non-interactive.
* If the caller already supplied `--no-interaction` under any of its
* aliases, their value is preserved.
* - `true` forces the sub-command non-interactive regardless of the
* parent, again deferring to a caller-supplied value if present.
* - `false` strips any inherited or propagated `--no-interaction` so the
* sub-command resolves its own state. TTY detection can still force
* non-interactive if STDIN is not a TTY.
*
* @param array<string, list<string|null>|string|null> $options
*
* @return array<string, list<string|null>|string|null>
*/
private function resolveChildInteractiveState(array $options, ?bool $noInteractionOverride): array
{
$this->assertOptionIsDefined('no-interaction');
if ($noInteractionOverride === false) {
$definition = $this->optionsDefinition['no-interaction'];
$aliases = array_filter(
[$definition->name, $definition->shortcut, $definition->negation],
static fn (?string $alias): bool => $alias !== null,
);
foreach ($aliases as $alias) {
unset($options[$alias]);
}
return $options;
}
if ($this->hasUnboundOption('no-interaction', $options)) {
return $options;
}
if ($noInteractionOverride === true || ! $this->isInteractive()) {
$options['no-interaction'] = null; // simulate --no-interaction being passed
}
return $options;
}
/**
* Binds the given raw arguments and options to the command's arguments and options
* definitions, and returns the bound arguments and options.
*
* @param list<string> $arguments Parsed arguments from command line.
* @param array<string, list<string|null>|string|null> $options Parsed options from command line.
*
* @return array{
* 0: array<string, list<string>|string>,
* 1: array<string, bool|list<bool|string>|string|null>,
* }
*/
private function bind(array $arguments, array $options): array
{
$boundArguments = [];
$boundOptions = [];
// 1. Arguments are position-based, so we will bind them in the order they are defined
// as well as the order they are given in the command line.
foreach ($this->argumentsDefinition as $name => $definition) {
if ($definition->isArray) {
if ($arguments !== []) {
$boundArguments[$name] = array_values($arguments);
$arguments = [];
} elseif (! $definition->required) {
$boundArguments[$name] = $definition->default;
}
} elseif ($definition->required) {
$argument = array_shift($arguments);
if ($argument === null) {
continue; // Missing required argument. To skip for validation to catch later.
}
$boundArguments[$name] = $argument;
} else {
$boundArguments[$name] = array_shift($arguments) ?? $definition->default;
}
}
// 2. If there are still arguments left that are not defined, we will mark them as extraneous.
if ($arguments !== []) {
$boundArguments['extra_arguments'] = array_values($arguments);
}
// 3. Options are name-based, so we will bind them by their names, shortcuts, and negations.
// Passed flag options will be set to `true`, otherwise, they will be set to `false`.
// Options that accept values will be set to the value passed or their default value if not passed.
// Negatable options will be set to `false` if the negation is passed.
foreach ($this->optionsDefinition as $name => $definition) {
if (array_key_exists($name, $options)) {
$boundOptions[$name] = $options[$name];
unset($options[$name]);
} elseif ($definition->shortcut !== null && array_key_exists($definition->shortcut, $options)) {
$boundOptions[$name] = $options[$definition->shortcut];
unset($options[$definition->shortcut]);
} elseif ($definition->negation !== null && array_key_exists($definition->negation, $options)) {
$boundOptions[$name] = $options[$definition->negation] ?? false;
if (is_array($boundOptions[$name])) {
// Edge case: passing a negated option multiple times should normalize to false
$boundOptions[$name] = array_map(static fn (mixed $v): mixed => $v ?? false, $boundOptions[$name]);
}
unset($options[$definition->negation]);
} else {
$boundOptions[$name] = $definition->default;
}
if ($definition->isArray && ! is_array($boundOptions[$name])) {
$boundOptions[$name] = [$boundOptions[$name]];
} elseif (! $definition->acceptsValue && ! $definition->negatable) {
$boundOptions[$name] ??= true;
} elseif ($definition->negatable) {
if (is_array($boundOptions[$name])) {
$boundOptions[$name] = array_map(static fn (mixed $v): mixed => $v ?? true, $boundOptions[$name]);
} else {
$boundOptions[$name] ??= true;
}
}
}
// 4. If there are still options left that are not defined, we will mark them as extraneous.
foreach ($options as $name => $value) {
if ($this->hasShortcut($name)) {
// This scenario can happen when the command has an array option with a shortcut,
// and the shortcut is used alongside the long name, causing it to be not bound
// in the previous loop. The leftover shortcut value can itself be an array when
// the shortcut was passed multiple times, so merge arrays and append scalars.
$option = $this->shortcuts[$name];
$values = is_array($value) ? $value : [$value];
if (array_key_exists($option, $boundOptions) && is_array($boundOptions[$option])) {
$boundOptions[$option] = [...$boundOptions[$option], ...$values];
} else {
$boundOptions[$option] = [$boundOptions[$option], ...$values];
}
continue;
}
if ($this->hasNegation($name)) {
// This scenario can happen when the command has a negatable option,
// and both the option and its negation are used, causing the negation
// to be not bound in the previous loop. The leftover negation value can
// be scalar (including a string when the negation was passed with a value)
// or an array — normalise to an array before mapping null → false.
$option = $this->negations[$name];
$values = is_array($value) ? $value : [$value];
$values = array_map(static fn (mixed $v): mixed => $v ?? false, $values);
if (! is_array($boundOptions[$option])) {
$boundOptions[$option] = [$boundOptions[$option]];
}
$boundOptions[$option] = [...$boundOptions[$option], ...$values];
continue;
}
$boundOptions['extra_options'] ??= [];
$boundOptions['extra_options'][$name] = $value;
}
return [$boundArguments, $boundOptions];
}
/**
* Validates the bound arguments and options.
*
* @param array<string, list<string>|string> $arguments Bound arguments using the command's arguments definition.
* @param array<string, bool|list<bool|string|null>|string|null> $options Bound options using the command's options definition.
*
* @throws ArgumentCountMismatchException
* @throws LogicException
* @throws OptionValueMismatchException
* @throws UnknownOptionException
*/
private function validate(array $arguments, array $options): void
{
$this->validateArguments($arguments);
foreach ($this->optionsDefinition as $name => $definition) {
$this->validateOption($name, $definition, $options[$name]);
}
if (array_key_exists('extra_options', $options)) {
throw new UnknownOptionException(lang('Commands.unknownOptions', [
count($options['extra_options']),
$this->name,
implode(', ', array_map(
static fn (string $key): string => strlen($key) === 1 ? sprintf('-%s', $key) : sprintf('--%s', $key),
array_keys($options['extra_options']),
)),
]));
}
}
/**
* @param array<string, list<string>|string> $arguments
*
* @throws ArgumentCountMismatchException
*/
private function validateArguments(array $arguments): void
{
if ($this->argumentsDefinition === [] && $arguments !== []) {
assert(array_key_exists('extra_arguments', $arguments));
throw new ArgumentCountMismatchException(lang('Commands.noArgumentsExpected', [
$this->name,
implode('", "', $arguments['extra_arguments']),
]));
}
if (array_diff($this->requiredArguments, array_keys($arguments)) !== []) {
throw new ArgumentCountMismatchException(lang('Commands.missingRequiredArguments', [
$this->name,
count($this->requiredArguments),
implode(', ', $this->requiredArguments),
]));
}
if (array_key_exists('extra_arguments', $arguments)) {
throw new ArgumentCountMismatchException(lang('Commands.tooManyArguments', [
$this->name,
count($arguments['extra_arguments']),
implode('", "', $arguments['extra_arguments']),
]));
}
}
/**
* @param bool|list<bool|string|null>|string|null $value
*
* @throws LogicException
* @throws OptionValueMismatchException
*/
private function validateOption(string $name, Option $definition, array|bool|string|null $value): void
{
if (! $definition->acceptsValue && ! $definition->negatable) {
if (is_array($value) && ! $definition->isArray) {
throw new LogicException(lang('Commands.flagOptionPassedMultipleTimes', [$name]));
}
if (! is_bool($value)) {
throw new OptionValueMismatchException(lang('Commands.optionNotAcceptingValue', [$name]));
}
}
if ($definition->acceptsValue && ! $definition->isArray && is_array($value)) {
throw new OptionValueMismatchException(lang('Commands.nonArrayOptionWithArrayValue', [$name]));
}
if ($definition->requiresValue) {
$elements = is_array($value) ? $value : [$value];
foreach ($elements as $element) {
if (! is_string($element)) {
throw new OptionValueMismatchException(lang('Commands.optionRequiresValue', [$name]));
}
}
}
if (! $definition->negatable || is_bool($value)) {
return;
}
$this->validateNegatableOption($name, $definition, $value);
}
/**
* @param list<bool|string|null>|string|null $value
*
* @throws LogicException
* @throws OptionValueMismatchException
*/
private function validateNegatableOption(string $name, Option $definition, array|string|null $value): void
{
if (! is_array($value)) {
if (array_key_exists($name, $this->unboundOptions)) {
throw new OptionValueMismatchException(lang('Commands.negatableOptionNoValue', [$name]));
}
throw new OptionValueMismatchException(lang('Commands.negatedOptionNoValue', [$definition->negation]));
}
// Both forms appearing together is the primary user mistake; flag it
// regardless of whether either form carried a value.
if (
array_key_exists($name, $this->unboundOptions)
&& array_key_exists($definition->negation, $this->unboundOptions)
) {
throw new LogicException(lang('Commands.negatableOptionWithNegation', [$name, $definition->negation]));
}
if (array_key_exists($name, $this->unboundOptions)) {
throw new OptionValueMismatchException(lang('Commands.negatableOptionPassedMultipleTimes', [$name]));
}
throw new OptionValueMismatchException(lang('Commands.negatedOptionPassedMultipleTimes', [$definition->negation]));
}
/**
* @throws LogicException
*/
private function assertOptionIsDefined(string $name): void