Debian Codegraph @

vendor/symfony/console/Command/Command.php

raw
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Console\Command;
13
14 use Symfony\Component\Console\Application;
15 use Symfony\Component\Console\Attribute\AsCommand;
16 use Symfony\Component\Console\Completion\CompletionInput;
17 use Symfony\Component\Console\Completion\CompletionSuggestions;
18 use Symfony\Component\Console\Completion\Suggestion;
19 use Symfony\Component\Console\Exception\ExceptionInterface;
20 use Symfony\Component\Console\Exception\InvalidArgumentException;
21 use Symfony\Component\Console\Exception\LogicException;
22 use Symfony\Component\Console\Helper\HelperInterface;
23 use Symfony\Component\Console\Helper\HelperSet;
24 use Symfony\Component\Console\Input\InputArgument;
25 use Symfony\Component\Console\Input\InputDefinition;
26 use Symfony\Component\Console\Input\InputInterface;
27 use Symfony\Component\Console\Input\InputOption;
28 use Symfony\Component\Console\Output\OutputInterface;
29
30 /**
31 * Base class for all commands.
32 *
33 * @author Fabien Potencier <[email protected]>
34 */
35 class Command implements SignalableCommandInterface
36 {
37 // see https://tldp.org/LDP/abs/html/exitcodes.html
38 public const SUCCESS = 0;
39 public const FAILURE = 1;
40 public const INVALID = 2;
41
42 private ?Application $application = null;
43 private ?string $name = null;
44 private ?string $processTitle = null;
45 private array $aliases = [];
46 private InputDefinition $definition;
47 private bool $hidden = false;
48 private string $help = '';
49 private string $description = '';
50 private ?InputDefinition $fullDefinition = null;
51 private bool $ignoreValidationErrors = false;
52 private ?InvokableCommand $code = null;
53 private array $synopsis = [];
54 private array $usages = [];
55 private ?HelperSet $helperSet = null;
56
57 /**
58 * @deprecated since Symfony 7.3, use the #[AsCommand] attribute instead
59 */
60 public static function getDefaultName(): ?string
61 {
62 trigger_deprecation('symfony/console', '7.3', 'Method "%s()" is deprecated and will be removed in Symfony 8.0, use the #[AsCommand] attribute instead.', __METHOD__);
63
64 if ($attribute = (new \ReflectionClass(static::class))->getAttributes(AsCommand::class)) {
65 return $attribute[0]->newInstance()->name;
66 }
67
68 return null;
69 }
70
71 /**
72 * @deprecated since Symfony 7.3, use the #[AsCommand] attribute instead
73 */
74 public static function getDefaultDescription(): ?string
75 {
76 trigger_deprecation('symfony/console', '7.3', 'Method "%s()" is deprecated and will be removed in Symfony 8.0, use the #[AsCommand] attribute instead.', __METHOD__);
77
78 if ($attribute = (new \ReflectionClass(static::class))->getAttributes(AsCommand::class)) {
79 return $attribute[0]->newInstance()->description;
80 }
81
82 return null;
83 }
84
85 /**
86 * @param string|null $name The name of the command; passing null means it must be set in configure()
87 *
88 * @throws LogicException When the command name is empty
89 */
90 public function __construct(?string $name = null, ?callable $code = null)
91 {
92 if (null !== $code) {
93 if (!\is_object($code) || $code instanceof \Closure) {
94 throw new InvalidArgumentException(\sprintf('The command must be an instance of "%s" or an invokable object.', self::class));
95 }
96 /** @var AsCommand $attribute */
97 $attribute = ((new \ReflectionObject($code))->getAttributes(AsCommand::class)[0] ?? null)?->newInstance()
98 ?? throw new LogicException(\sprintf('The command must use the "%s" attribute.', AsCommand::class));
99 $this->setCode($code);
100 } else {
101 $attribute = ((new \ReflectionClass(static::class))->getAttributes(AsCommand::class)[0] ?? null)?->newInstance();
102 }
103
104 $this->definition = new InputDefinition();
105 if (null === $name) {
106 if (self::class !== (new \ReflectionMethod($this, 'getDefaultName'))->class) {
107 trigger_deprecation('symfony/console', '7.3', 'Overriding "Command::getDefaultName()" in "%s" is deprecated and will be removed in Symfony 8.0, use the #[AsCommand] attribute instead.', static::class);
108
109 $name = static::getDefaultName();
110 } else {
111 $name = $attribute?->name;
112 }
113 }
114
115 if (null !== $name) {
116 $aliases = explode('|', $name);
117
118 if ('' === $name = array_shift($aliases)) {
119 $this->setHidden(true);
120 $name = array_shift($aliases);
121 }
122
123 // we must not overwrite existing aliases, combine new ones with existing ones
124 $aliases = array_unique([
125 ...$this->aliases,
126 ...$aliases,
127 ]);
128
129 $this->setAliases($aliases);
130 }
131
132 if (null !== $name) {
133 $this->setName($name);
134 }
135
136 if ('' === $this->description) {
137 if (self::class !== (new \ReflectionMethod($this, 'getDefaultDescription'))->class) {
138 trigger_deprecation('symfony/console', '7.3', 'Overriding "Command::getDefaultDescription()" in "%s" is deprecated and will be removed in Symfony 8.0, use the #[AsCommand] attribute instead.', static::class);
139
140 $defaultDescription = static::getDefaultDescription();
141 } else {
142 $defaultDescription = $attribute?->description;
143 }
144
145 $this->setDescription($defaultDescription ?? '');
146 }
147
148 if ('' === $this->help) {
149 $this->setHelp($attribute?->help ?? '');
150 }
151
152 foreach ($attribute?->usages ?? [] as $usage) {
153 $this->addUsage($usage);
154 }
155
156 if (!$code && \is_callable($this) && self::class === (new \ReflectionMethod($this, 'execute'))->getDeclaringClass()->name) {
157 $this->code = new InvokableCommand($this, $this(...));
158 }
159
160 $this->configure();
161 }
162
163 /**
164 * Ignores validation errors.
165 *
166 * This is mainly useful for the help command.
167 */
168 public function ignoreValidationErrors(): void
169 {
170 $this->ignoreValidationErrors = true;
171 }
172
173 public function setApplication(?Application $application): void
174 {
175 $this->application = $application;
176 if ($application) {
177 $this->setHelperSet($application->getHelperSet());
178 } else {
179 $this->helperSet = null;
180 }
181
182 $this->fullDefinition = null;
183 }
184
185 public function setHelperSet(HelperSet $helperSet): void
186 {
187 $this->helperSet = $helperSet;
188 }
189
190 /**
191 * Gets the helper set.
192 */
193 public function getHelperSet(): ?HelperSet
194 {
195 return $this->helperSet;
196 }
197
198 /**
199 * Gets the application instance for this command.
200 */
201 public function getApplication(): ?Application
202 {
203 return $this->application;
204 }
205
206 /**
207 * Checks whether the command is enabled or not in the current environment.
208 *
209 * Override this to check for x or y and return false if the command cannot
210 * run properly under the current conditions.
211 */
212 public function isEnabled(): bool
213 {
214 return true;
215 }
216
217 /**
218 * Configures the current command.
219 *
220 * @return void
221 */
222 protected function configure()
223 {
224 }
225
226 /**
227 * Executes the current command.
228 *
229 * This method is not abstract because you can use this class
230 * as a concrete class. In this case, instead of defining the
231 * execute() method, you set the code to execute by passing
232 * a Closure to the setCode() method.
233 *
234 * @return int 0 if everything went fine, or an exit code
235 *
236 * @throws LogicException When this abstract method is not implemented
237 *
238 * @see setCode()
239 */
240 protected function execute(InputInterface $input, OutputInterface $output): int
241 {
242 throw new LogicException('You must override the execute() method in the concrete command class.');
243 }
244
245 /**
246 * Interacts with the user.
247 *
248 * This method is executed before the InputDefinition is validated.
249 * This means that this is the only place where the command can
250 * interactively ask for values of missing required arguments.
251 *
252 * @return void
253 */
254 protected function interact(InputInterface $input, OutputInterface $output)
255 {
256 }
257
258 /**
259 * Initializes the command after the input has been bound and before the input
260 * is validated.
261 *
262 * This is mainly useful when a lot of commands extends one main command
263 * where some things need to be initialized based on the input arguments and options.
264 *
265 * @see InputInterface::bind()
266 * @see InputInterface::validate()
267 *
268 * @return void
269 */
270 protected function initialize(InputInterface $input, OutputInterface $output)
271 {
272 }
273
274 /**
275 * Runs the command.
276 *
277 * The code to execute is either defined directly with the
278 * setCode() method or by overriding the execute() method
279 * in a sub-class.
280 *
281 * @return int The command exit code
282 *
283 * @throws ExceptionInterface When input binding fails. Bypass this by calling {@link ignoreValidationErrors()}.
284 *
285 * @see setCode()
286 * @see execute()
287 */
288 public function run(InputInterface $input, OutputInterface $output): int
289 {
290 // add the application arguments and options
291 $this->mergeApplicationDefinition();
292
293 // bind the input against the command specific arguments/options
294 try {
295 $input->bind($this->getDefinition());
296 } catch (ExceptionInterface $e) {
297 if (!$this->ignoreValidationErrors) {
298 throw $e;
299 }
300 }
301
302 $this->initialize($input, $output);
303
304 if (null !== $this->processTitle) {
305 if (\function_exists('cli_set_process_title')) {
306 if (!@cli_set_process_title($this->processTitle)) {
307 if ('Darwin' === \PHP_OS) {
308 $output->writeln('<comment>Running "cli_set_process_title" as an unprivileged user is not supported on MacOS.</comment>', OutputInterface::VERBOSITY_VERY_VERBOSE);
309 } else {
310 cli_set_process_title($this->processTitle);
311 }
312 }
313 } elseif (\function_exists('setproctitle')) {
314 setproctitle($this->processTitle);
315 } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
316 $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
317 }
318 }
319
320 if ($input->isInteractive()) {
321 $this->interact($input, $output);
322
323 if ($this->code?->isInteractive()) {
324 $this->code->interact($input, $output);
325 }
326 }
327
328 // The command name argument is often omitted when a command is executed directly with its run() method.
329 // It would fail the validation if we didn't make sure the command argument is present,
330 // since it's required by the application.
331 if ($input->hasArgument('command') && null === $input->getArgument('command')) {
332 $input->setArgument('command', $this->getName());
333 }
334
335 $input->validate();
336
337 if ($this->code) {
338 return ($this->code)($input, $output);
339 }
340
341 return $this->execute($input, $output);
342 }
343
344 /**
345 * Supplies suggestions when resolving possible completion options for input (e.g. option or argument).
346 */
347 public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
348 {
349 $definition = $this->getDefinition();
350 if (CompletionInput::TYPE_OPTION_VALUE === $input->getCompletionType() && $definition->hasOption($input->getCompletionName())) {
351 $definition->getOption($input->getCompletionName())->complete($input, $suggestions);
352 } elseif (CompletionInput::TYPE_ARGUMENT_VALUE === $input->getCompletionType() && $definition->hasArgument($input->getCompletionName())) {
353 $definition->getArgument($input->getCompletionName())->complete($input, $suggestions);
354 }
355 }
356
357 /**
358 * Gets the code that is executed by the command.
359 *
360 * @return ?callable null if the code has not been set with setCode()
361 */
362 public function getCode(): ?callable
363 {
364 return $this->code?->getCode();
365 }
366
367 /**
368 * Sets the code to execute when running this command.
369 *
370 * If this method is used, it overrides the code defined
371 * in the execute() method.
372 *
373 * @param callable $code A callable(InputInterface $input, OutputInterface $output)
374 *
375 * @return $this
376 *
377 * @throws InvalidArgumentException
378 *
379 * @see execute()
380 */
381 public function setCode(callable $code): static
382 {
383 $this->code = new InvokableCommand($this, $code);
384
385 return $this;
386 }
387
388 /**
389 * Merges the application definition with the command definition.
390 *
391 * This method is not part of public API and should not be used directly.
392 *
393 * @param bool $mergeArgs Whether to merge or not the Application definition arguments to Command definition arguments
394 *
395 * @internal
396 */
397 public function mergeApplicationDefinition(bool $mergeArgs = true): void
398 {
399 if (null === $this->application) {
400 return;
401 }
402
403 $this->fullDefinition = new InputDefinition();
404 $this->fullDefinition->setOptions($this->definition->getOptions());
405 $this->fullDefinition->addOptions($this->application->getDefinition()->getOptions());
406
407 if ($mergeArgs) {
408 $this->fullDefinition->setArguments($this->application->getDefinition()->getArguments());
409 $this->fullDefinition->addArguments($this->definition->getArguments());
410 } else {
411 $this->fullDefinition->setArguments($this->definition->getArguments());
412 }
413 }
414
415 /**
416 * Sets an array of argument and option instances.
417 *
418 * @return $this
419 */
420 public function setDefinition(array|InputDefinition $definition): static
421 {
422 if ($definition instanceof InputDefinition) {
423 $this->definition = $definition;
424 } else {
425 $this->definition->setDefinition($definition);
426 }
427
428 $this->fullDefinition = null;
429
430 return $this;
431 }
432
433 /**
434 * Gets the InputDefinition attached to this Command.
435 */
436 public function getDefinition(): InputDefinition
437 {
438 return $this->fullDefinition ?? $this->getNativeDefinition();
439 }
440
441 /**
442 * Gets the InputDefinition to be used to create representations of this Command.
443 *
444 * Can be overridden to provide the original command representation when it would otherwise
445 * be changed by merging with the application InputDefinition.
446 *
447 * This method is not part of public API and should not be used directly.
448 */
449 public function getNativeDefinition(): InputDefinition
450 {
451 $definition = $this->definition ?? throw new LogicException(\sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', static::class));
452
453 if ($this->code && !$definition->getArguments() && !$definition->getOptions()) {
454 $this->code->configure($definition);
455 }
456
457 return $definition;
458 }
459
460 /**
461 * Adds an argument.
462 *
463 * @param $mode The argument mode: InputArgument::REQUIRED or InputArgument::OPTIONAL
464 * @param $default The default value (for InputArgument::OPTIONAL mode only)
465 * @param array|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> $suggestedValues The values used for input completion
466 *
467 * @return $this
468 *
469 * @throws InvalidArgumentException When argument mode is not valid
470 */
471 public function addArgument(string $name, ?int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static
472 {
473 $this->definition->addArgument(new InputArgument($name, $mode, $description, $default, $suggestedValues));
474 $this->fullDefinition?->addArgument(new InputArgument($name, $mode, $description, $default, $suggestedValues));
475
476 return $this;
477 }
478
479 /**
480 * Adds an option.
481 *
482 * @param $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts
483 * @param $mode The option mode: One of the InputOption::VALUE_* constants
484 * @param $default The default value (must be null for InputOption::VALUE_NONE)
485 * @param array|\Closure(CompletionInput,CompletionSuggestions):list<string|Suggestion> $suggestedValues The values used for input completion
486 *
487 * @return $this
488 *
489 * @throws InvalidArgumentException If option mode is invalid or incompatible
490 */
491 public function addOption(string $name, string|array|null $shortcut = null, ?int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static
492 {
493 $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default, $suggestedValues));
494 $this->fullDefinition?->addOption(new InputOption($name, $shortcut, $mode, $description, $default, $suggestedValues));
495
496 return $this;
497 }
498
499 /**
500 * Sets the name of the command.
501 *
502 * This method can set both the namespace and the name if
503 * you separate them by a colon (:)
504 *
505 * $command->setName('foo:bar');
506 *
507 * @return $this
508 *
509 * @throws InvalidArgumentException When the name is invalid
510 */
511 public function setName(string $name): static
512 {
513 $this->validateName($name);
514
515 $this->name = $name;
516
517 return $this;
518 }
519
520 /**
521 * Sets the process title of the command.
522 *
523 * This feature should be used only when creating a long process command,
524 * like a daemon.
525 *
526 * @return $this
527 */
528 public function setProcessTitle(string $title): static
529 {
530 $this->processTitle = $title;
531
532 return $this;
533 }
534
535 /**
536 * Returns the command name.
537 */
538 public function getName(): ?string
539 {
540 return $this->name;
541 }
542
543 /**
544 * @param bool $hidden Whether or not the command should be hidden from the list of commands
545 *
546 * @return $this
547 */
548 public function setHidden(bool $hidden = true): static
549 {
550 $this->hidden = $hidden;
551
552 return $this;
553 }
554
555 /**
556 * @return bool whether the command should be publicly shown or not
557 */
558 public function isHidden(): bool
559 {
560 return $this->hidden;
561 }
562
563 /**
564 * Sets the description for the command.
565 *
566 * @return $this
567 */
568 public function setDescription(string $description): static
569 {
570 $this->description = $description;
571
572 return $this;
573 }
574
575 /**
576 * Returns the description for the command.
577 */
578 public function getDescription(): string
579 {
580 return $this->description;
581 }
582
583 /**
584 * Sets the help for the command.
585 *
586 * @return $this
587 */
588 public function setHelp(string $help): static
589 {
590 $this->help = $help;
591
592 return $this;
593 }
594
595 /**
596 * Returns the help for the command.
597 */
598 public function getHelp(): string
599 {
600 return $this->help;
601 }
602
603 /**
604 * Returns the processed help for the command replacing the %command.name% and
605 * %command.full_name% patterns with the real values dynamically.
606 */
607 public function getProcessedHelp(): string
608 {
609 $name = $this->name;
610 $isSingleCommand = $this->application?->isSingleCommand();
611
612 $placeholders = [
613 '%command.name%',
614 '%command.full_name%',
615 ];
616 $replacements = [
617 $name,
618 $isSingleCommand ? $_SERVER['PHP_SELF'] : $_SERVER['PHP_SELF'].' '.$name,
619 ];
620
621 return str_replace($placeholders, $replacements, $this->getHelp() ?: $this->getDescription());
622 }
623
624 /**
625 * Sets the aliases for the command.
626 *
627 * @param string[] $aliases An array of aliases for the command
628 *
629 * @return $this
630 *
631 * @throws InvalidArgumentException When an alias is invalid
632 */
633 public function setAliases(iterable $aliases): static
634 {
635 $list = [];
636
637 foreach ($aliases as $alias) {
638 $this->validateName($alias);
639 $list[] = $alias;
640 }
641
642 $this->aliases = \is_array($aliases) ? $aliases : $list;
643
644 return $this;
645 }
646
647 /**
648 * Returns the aliases for the command.
649 */
650 public function getAliases(): array
651 {
652 return $this->aliases;
653 }
654
655 /**
656 * Returns the synopsis for the command.
657 *
658 * @param bool $short Whether to show the short version of the synopsis (with options folded) or not
659 */
660 public function getSynopsis(bool $short = false): string
661 {
662 $key = $short ? 'short' : 'long';
663
664 if (!isset($this->synopsis[$key])) {
665 $this->synopsis[$key] = trim(\sprintf('%s %s', $this->name, $this->definition->getSynopsis($short)));
666 }
667
668 return $this->synopsis[$key];
669 }
670
671 /**
672 * Add a command usage example, it'll be prefixed with the command name.
673 *
674 * @return $this
675 */
676 public function addUsage(string $usage): static
677 {
678 if (!str_starts_with($usage, $this->name)) {
679 $usage = \sprintf('%s %s', $this->name, $usage);
680 }
681
682 $this->usages[] = $usage;
683
684 return $this;
685 }
686
687 /**
688 * Returns alternative usages of the command.
689 */
690 public function getUsages(): array
691 {
692 return $this->usages;
693 }
694
695 /**
696 * Gets a helper instance by name.
697 *
698 * @throws LogicException if no HelperSet is defined
699 * @throws InvalidArgumentException if the helper is not defined
700 */
701 public function getHelper(string $name): HelperInterface
702 {
703 if (null === $this->helperSet) {
704 throw new LogicException(\sprintf('Cannot retrieve helper "%s" because there is no HelperSet defined. Did you forget to add your command to the application or to set the application on the command using the setApplication() method? You can also set the HelperSet directly using the setHelperSet() method.', $name));
705 }
706
707 return $this->helperSet->get($name);
708 }
709
710 public function getSubscribedSignals(): array
711 {
712 return $this->code?->getSubscribedSignals() ?? [];
713 }
714
715 public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false
716 {
717 return $this->code?->handleSignal($signal, $previousExitCode) ?? false;
718 }
719
720 /**
721 * Validates a command name.
722 *
723 * It must be non-empty and parts can optionally be separated by ":".
724 *
725 * @throws InvalidArgumentException When the name is invalid
726 */
727 private function validateName(string $name): void
728 {
729 if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
730 throw new InvalidArgumentException(\sprintf('Command name "%s" is invalid.', $name));
731 }
732 }
733 }