Debian Codegraph @

vendor/symfony/console/Application.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;
13
14 use Symfony\Component\Console\Command\Command;
15 use Symfony\Component\Console\Command\CompleteCommand;
16 use Symfony\Component\Console\Command\DumpCompletionCommand;
17 use Symfony\Component\Console\Command\HelpCommand;
18 use Symfony\Component\Console\Command\LazyCommand;
19 use Symfony\Component\Console\Command\ListCommand;
20 use Symfony\Component\Console\CommandLoader\CommandLoaderInterface;
21 use Symfony\Component\Console\Completion\CompletionInput;
22 use Symfony\Component\Console\Completion\CompletionSuggestions;
23 use Symfony\Component\Console\Completion\Suggestion;
24 use Symfony\Component\Console\Event\ConsoleAlarmEvent;
25 use Symfony\Component\Console\Event\ConsoleCommandEvent;
26 use Symfony\Component\Console\Event\ConsoleErrorEvent;
27 use Symfony\Component\Console\Event\ConsoleSignalEvent;
28 use Symfony\Component\Console\Event\ConsoleTerminateEvent;
29 use Symfony\Component\Console\Exception\CommandNotFoundException;
30 use Symfony\Component\Console\Exception\ExceptionInterface;
31 use Symfony\Component\Console\Exception\LogicException;
32 use Symfony\Component\Console\Exception\NamespaceNotFoundException;
33 use Symfony\Component\Console\Exception\RuntimeException;
34 use Symfony\Component\Console\Formatter\OutputFormatter;
35 use Symfony\Component\Console\Helper\DebugFormatterHelper;
36 use Symfony\Component\Console\Helper\DescriptorHelper;
37 use Symfony\Component\Console\Helper\FormatterHelper;
38 use Symfony\Component\Console\Helper\Helper;
39 use Symfony\Component\Console\Helper\HelperSet;
40 use Symfony\Component\Console\Helper\ProcessHelper;
41 use Symfony\Component\Console\Helper\QuestionHelper;
42 use Symfony\Component\Console\Input\ArgvInput;
43 use Symfony\Component\Console\Input\ArrayInput;
44 use Symfony\Component\Console\Input\InputArgument;
45 use Symfony\Component\Console\Input\InputAwareInterface;
46 use Symfony\Component\Console\Input\InputDefinition;
47 use Symfony\Component\Console\Input\InputInterface;
48 use Symfony\Component\Console\Input\InputOption;
49 use Symfony\Component\Console\Output\ConsoleOutput;
50 use Symfony\Component\Console\Output\ConsoleOutputInterface;
51 use Symfony\Component\Console\Output\OutputInterface;
52 use Symfony\Component\Console\SignalRegistry\SignalRegistry;
53 use Symfony\Component\Console\Style\SymfonyStyle;
54 use Symfony\Component\ErrorHandler\ErrorHandler;
55 use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
56 use Symfony\Contracts\Service\ResetInterface;
57
58 /**
59 * An Application is the container for a collection of commands.
60 *
61 * It is the main entry point of a Console application.
62 *
63 * This class is optimized for a standard CLI environment.
64 *
65 * Usage:
66 *
67 * $app = new Application('myapp', '1.0 (stable)');
68 * $app->addCommand(new SimpleCommand());
69 * $app->run();
70 *
71 * @author Fabien Potencier <[email protected]>
72 */
73 class Application implements ResetInterface
74 {
75 private array $commands = [];
76 private bool $wantHelps = false;
77 private ?Command $runningCommand = null;
78 private ?CommandLoaderInterface $commandLoader = null;
79 private bool $catchExceptions = true;
80 private bool $catchErrors = false;
81 private bool $autoExit = true;
82 private InputDefinition $definition;
83 private HelperSet $helperSet;
84 private ?EventDispatcherInterface $dispatcher = null;
85 private Terminal $terminal;
86 private string $defaultCommand;
87 private bool $singleCommand = false;
88 private bool $initialized = false;
89 private ?SignalRegistry $signalRegistry = null;
90 private array $signalsToDispatchEvent = [];
91 private ?int $alarmInterval = null;
92
93 public function __construct(
94 private string $name = 'UNKNOWN',
95 private string $version = 'UNKNOWN',
96 ) {
97 $this->terminal = new Terminal();
98 $this->defaultCommand = 'list';
99 if (\defined('SIGINT') && SignalRegistry::isSupported()) {
100 $this->signalRegistry = new SignalRegistry();
101 $this->signalsToDispatchEvent = [\SIGINT, \SIGQUIT, \SIGTERM, \SIGUSR1, \SIGUSR2, \SIGALRM];
102 }
103 }
104
105 /**
106 * @final
107 */
108 public function setDispatcher(EventDispatcherInterface $dispatcher): void
109 {
110 $this->dispatcher = $dispatcher;
111 }
112
113 public function setCommandLoader(CommandLoaderInterface $commandLoader): void
114 {
115 $this->commandLoader = $commandLoader;
116 }
117
118 public function getSignalRegistry(): SignalRegistry
119 {
120 if (!$this->signalRegistry) {
121 throw new RuntimeException('Signals are not supported. Make sure that the "pcntl" extension is installed and that "pcntl_*" functions are not disabled by your php.ini\'s "disable_functions" directive.');
122 }
123
124 return $this->signalRegistry;
125 }
126
127 public function setSignalsToDispatchEvent(int ...$signalsToDispatchEvent): void
128 {
129 $this->signalsToDispatchEvent = $signalsToDispatchEvent;
130 }
131
132 /**
133 * Sets the interval to schedule a SIGALRM signal in seconds.
134 */
135 public function setAlarmInterval(?int $seconds): void
136 {
137 $this->alarmInterval = $seconds;
138 $this->scheduleAlarm();
139 }
140
141 /**
142 * Gets the interval in seconds on which a SIGALRM signal is dispatched.
143 */
144 public function getAlarmInterval(): ?int
145 {
146 return $this->alarmInterval;
147 }
148
149 private function scheduleAlarm(): void
150 {
151 if (null !== $this->alarmInterval) {
152 $this->getSignalRegistry()->scheduleAlarm($this->alarmInterval);
153 }
154 }
155
156 /**
157 * Runs the current application.
158 *
159 * @return int 0 if everything went fine, or an error code
160 *
161 * @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}.
162 */
163 public function run(?InputInterface $input = null, ?OutputInterface $output = null): int
164 {
165 if (\function_exists('putenv')) {
166 @putenv('LINES='.$this->terminal->getHeight());
167 @putenv('COLUMNS='.$this->terminal->getWidth());
168 }
169
170 $input ??= new ArgvInput();
171 $output ??= new ConsoleOutput();
172
173 $renderException = function (\Throwable $e) use ($output) {
174 if ($output instanceof ConsoleOutputInterface) {
175 $this->renderThrowable($e, $output->getErrorOutput());
176 } else {
177 $this->renderThrowable($e, $output);
178 }
179 };
180 if ($phpHandler = set_exception_handler($renderException)) {
181 restore_exception_handler();
182 if (!\is_array($phpHandler) || !$phpHandler[0] instanceof ErrorHandler) {
183 $errorHandler = true;
184 } elseif ($errorHandler = $phpHandler[0]->setExceptionHandler($renderException)) {
185 $phpHandler[0]->setExceptionHandler($errorHandler);
186 }
187 }
188
189 $empty = new \stdClass();
190 $prevShellVerbosity = [$_ENV['SHELL_VERBOSITY'] ?? $empty, $_SERVER['SHELL_VERBOSITY'] ?? $empty, getenv('SHELL_VERBOSITY')];
191
192 try {
193 $this->configureIO($input, $output);
194
195 $exitCode = $this->doRun($input, $output);
196 } catch (\Throwable $e) {
197 if ($e instanceof \Exception && !$this->catchExceptions) {
198 throw $e;
199 }
200 if (!$e instanceof \Exception && !$this->catchErrors) {
201 throw $e;
202 }
203
204 $renderException($e);
205
206 $exitCode = $e->getCode();
207 if (is_numeric($exitCode)) {
208 $exitCode = (int) $exitCode;
209 if ($exitCode <= 0) {
210 $exitCode = 1;
211 }
212 } else {
213 $exitCode = 1;
214 }
215 } finally {
216 // if the exception handler changed, keep it
217 // otherwise, unregister $renderException
218 if (!$phpHandler) {
219 if (set_exception_handler($renderException) === $renderException) {
220 restore_exception_handler();
221 }
222 restore_exception_handler();
223 } elseif (!$errorHandler) {
224 $finalHandler = $phpHandler[0]->setExceptionHandler(null);
225 if ($finalHandler !== $renderException) {
226 $phpHandler[0]->setExceptionHandler($finalHandler);
227 }
228 }
229
230 // SHELL_VERBOSITY is set by Application::configureIO so we need to unset/reset it
231 // to its previous value to avoid one command verbosity to spread to other commands
232 if ($empty === $_ENV['SHELL_VERBOSITY'] = $prevShellVerbosity[0]) {
233 unset($_ENV['SHELL_VERBOSITY']);
234 }
235 if ($empty === $_SERVER['SHELL_VERBOSITY'] = $prevShellVerbosity[1]) {
236 unset($_SERVER['SHELL_VERBOSITY']);
237 }
238 if (\function_exists('putenv')) {
239 @putenv('SHELL_VERBOSITY'.(false === ($prevShellVerbosity[2] ?? false) ? '' : '='.$prevShellVerbosity[2]));
240 }
241 }
242
243 if ($this->autoExit) {
244 if ($exitCode > 255) {
245 $exitCode = 255;
246 }
247
248 exit($exitCode);
249 }
250
251 return $exitCode;
252 }
253
254 /**
255 * Runs the current application.
256 *
257 * @return int 0 if everything went fine, or an error code
258 */
259 public function doRun(InputInterface $input, OutputInterface $output): int
260 {
261 if (true === $input->hasParameterOption(['--version', '-V'], true)) {
262 $output->writeln($this->getLongVersion());
263
264 return 0;
265 }
266
267 try {
268 // Makes ArgvInput::getFirstArgument() able to distinguish an option from an argument.
269 $input->bind($this->getDefinition());
270 } catch (ExceptionInterface) {
271 // Errors must be ignored, full binding/validation happens later when the command is known.
272 }
273
274 $name = $this->getCommandName($input);
275 if (true === $input->hasParameterOption(['--help', '-h'], true)) {
276 if (!$name) {
277 $name = 'help';
278 $input = new ArrayInput(['command_name' => $this->defaultCommand]);
279 } else {
280 $this->wantHelps = true;
281 }
282 }
283
284 if (!$name) {
285 $name = $this->defaultCommand;
286 $definition = $this->getDefinition();
287 $definition->setArguments(array_merge(
288 $definition->getArguments(),
289 [
290 'command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name),
291 ]
292 ));
293 }
294
295 try {
296 $this->runningCommand = null;
297 // the command name MUST be the first element of the input
298 $command = $this->find($name);
299 } catch (\Throwable $e) {
300 if (($e instanceof CommandNotFoundException && !$e instanceof NamespaceNotFoundException) && 1 === \count($alternatives = $e->getAlternatives()) && $input->isInteractive()) {
301 $alternative = $alternatives[0];
302
303 $style = new SymfonyStyle($input, $output);
304 $output->writeln('');
305 $formattedBlock = (new FormatterHelper())->formatBlock(\sprintf('Command "%s" is not defined.', $name), 'error', true);
306 $output->writeln($formattedBlock);
307 if (!$style->confirm(\sprintf('Do you want to run "%s" instead? ', $alternative), false)) {
308 if (null !== $this->dispatcher) {
309 $event = new ConsoleErrorEvent($input, $output, $e);
310 $this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
311
312 return $event->getExitCode();
313 }
314
315 return 1;
316 }
317
318 $command = $this->find($alternative);
319 } else {
320 if (null !== $this->dispatcher) {
321 $event = new ConsoleErrorEvent($input, $output, $e);
322 $this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
323
324 if (0 === $event->getExitCode()) {
325 return 0;
326 }
327
328 $e = $event->getError();
329 }
330
331 try {
332 if ($e instanceof CommandNotFoundException && $namespace = $this->findNamespace($name)) {
333 $helper = new DescriptorHelper();
334 $helper->describe($output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output, $this, [
335 'format' => 'txt',
336 'raw_text' => false,
337 'namespace' => $namespace,
338 'short' => false,
339 ]);
340
341 return isset($event) ? $event->getExitCode() : 1;
342 }
343
344 throw $e;
345 } catch (NamespaceNotFoundException) {
346 throw $e;
347 }
348 }
349 }
350
351 if ($command instanceof LazyCommand) {
352 $command = $command->getCommand();
353 }
354
355 $this->runningCommand = $command;
356 $exitCode = $this->doRunCommand($command, $input, $output);
357 $this->runningCommand = null;
358
359 return $exitCode;
360 }
361
362 public function reset(): void
363 {
364 }
365
366 public function setHelperSet(HelperSet $helperSet): void
367 {
368 $this->helperSet = $helperSet;
369 }
370
371 /**
372 * Get the helper set associated with the command.
373 */
374 public function getHelperSet(): HelperSet
375 {
376 return $this->helperSet ??= $this->getDefaultHelperSet();
377 }
378
379 public function setDefinition(InputDefinition $definition): void
380 {
381 $this->definition = $definition;
382 }
383
384 /**
385 * Gets the InputDefinition related to this Application.
386 */
387 public function getDefinition(): InputDefinition
388 {
389 $this->definition ??= $this->getDefaultInputDefinition();
390
391 if ($this->singleCommand) {
392 $this->definition->setArguments();
393 }
394
395 return $this->definition;
396 }
397
398 /**
399 * Adds suggestions to $suggestions for the current completion input (e.g. option or argument).
400 */
401 public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
402 {
403 if (
404 CompletionInput::TYPE_ARGUMENT_VALUE === $input->getCompletionType()
405 && 'command' === $input->getCompletionName()
406 ) {
407 foreach ($this->all() as $name => $command) {
408 // skip hidden commands and aliased commands as they already get added below
409 if ($command->isHidden() || $command->getName() !== $name) {
410 continue;
411 }
412 $suggestions->suggestValue(new Suggestion($command->getName(), $command->getDescription()));
413 foreach ($command->getAliases() as $name) {
414 $suggestions->suggestValue(new Suggestion($name, $command->getDescription()));
415 }
416 }
417
418 return;
419 }
420
421 if (CompletionInput::TYPE_OPTION_NAME === $input->getCompletionType()) {
422 $suggestions->suggestOptions($this->getDefinition()->getOptions());
423 }
424
425 if (
426 CompletionInput::TYPE_OPTION_VALUE === $input->getCompletionType()
427 && ($definition = $this->getDefinition())->hasOption($input->getCompletionName())
428 ) {
429 $definition->getOption($input->getCompletionName())->complete($input, $suggestions);
430
431 return;
432 }
433 }
434
435 /**
436 * Gets the help message.
437 */
438 public function getHelp(): string
439 {
440 return $this->getLongVersion();
441 }
442
443 /**
444 * Gets whether to catch exceptions or not during commands execution.
445 */
446 public function areExceptionsCaught(): bool
447 {
448 return $this->catchExceptions;
449 }
450
451 /**
452 * Sets whether to catch exceptions or not during commands execution.
453 */
454 public function setCatchExceptions(bool $boolean): void
455 {
456 $this->catchExceptions = $boolean;
457 }
458
459 /**
460 * Sets whether to catch errors or not during commands execution.
461 */
462 public function setCatchErrors(bool $catchErrors = true): void
463 {
464 $this->catchErrors = $catchErrors;
465 }
466
467 /**
468 * Gets whether to automatically exit after a command execution or not.
469 */
470 public function isAutoExitEnabled(): bool
471 {
472 return $this->autoExit;
473 }
474
475 /**
476 * Sets whether to automatically exit after a command execution or not.
477 */
478 public function setAutoExit(bool $boolean): void
479 {
480 $this->autoExit = $boolean;
481 }
482
483 /**
484 * Gets the name of the application.
485 */
486 public function getName(): string
487 {
488 return $this->name;
489 }
490
491 /**
492 * Sets the application name.
493 */
494 public function setName(string $name): void
495 {
496 $this->name = $name;
497 }
498
499 /**
500 * Gets the application version.
501 */
502 public function getVersion(): string
503 {
504 return $this->version;
505 }
506
507 /**
508 * Sets the application version.
509 */
510 public function setVersion(string $version): void
511 {
512 $this->version = $version;
513 }
514
515 /**
516 * Returns the long version of the application.
517 */
518 public function getLongVersion(): string
519 {
520 if ('UNKNOWN' !== $this->getName()) {
521 if ('UNKNOWN' !== $this->getVersion()) {
522 return \sprintf('%s <info>%s</info>', $this->getName(), $this->getVersion());
523 }
524
525 return $this->getName();
526 }
527
528 return 'Console Tool';
529 }
530
531 /**
532 * Registers a new command.
533 */
534 public function register(string $name): Command
535 {
536 return $this->addCommand(new Command($name));
537 }
538
539 /**
540 * Adds an array of command objects.
541 *
542 * If a Command is not enabled it will not be added.
543 *
544 * @param callable[]|Command[] $commands An array of commands
545 */
546 public function addCommands(array $commands): void
547 {
548 foreach ($commands as $command) {
549 $this->addCommand($command);
550 }
551 }
552
553 /**
554 * @deprecated since Symfony 7.4, use Application::addCommand() instead
555 */
556 public function add(Command $command): ?Command
557 {
558 trigger_deprecation('symfony/console', '7.4', 'The "%s()" method is deprecated and will be removed in Symfony 8.0, use "%s::addCommand()" instead.', __METHOD__, self::class);
559
560 return $this->addCommand($command);
561 }
562
563 /**
564 * Adds a command object.
565 *
566 * If a command with the same name already exists, it will be overridden.
567 * If the command is not enabled it will not be added.
568 */
569 public function addCommand(callable|Command $command): ?Command
570 {
571 $this->init();
572
573 if (!$command instanceof Command) {
574 $command = new Command(null, $command);
575 }
576
577 $command->setApplication($this);
578
579 if (!$command->isEnabled()) {
580 $command->setApplication(null);
581
582 return null;
583 }
584
585 if (!$command instanceof LazyCommand) {
586 // Will throw if the command is not correctly initialized.
587 $command->getDefinition();
588 }
589
590 if (!$command->getName()) {
591 throw new LogicException(\sprintf('The command defined in "%s" cannot have an empty name.', get_debug_type($command)));
592 }
593
594 $this->commands[$command->getName()] = $command;
595
596 foreach ($command->getAliases() as $alias) {
597 $this->commands[$alias] = $command;
598 }
599
600 return $command;
601 }
602
603 /**
604 * Returns a registered command by name or alias.
605 *
606 * @throws CommandNotFoundException When given command name does not exist
607 */
608 public function get(string $name): Command
609 {
610 $this->init();
611
612 if (!$this->has($name)) {
613 throw new CommandNotFoundException(\sprintf('The command "%s" does not exist.', $name));
614 }
615
616 // When the command has a different name than the one used at the command loader level
617 if (!isset($this->commands[$name])) {
618 throw new CommandNotFoundException(\sprintf('The "%s" command cannot be found because it is registered under multiple names. Make sure you don\'t set a different name via constructor or "setName()".', $name));
619 }
620
621 $command = $this->commands[$name];
622
623 if ($this->wantHelps) {
624 $this->wantHelps = false;
625
626 $helpCommand = $this->get('help');
627 $helpCommand->setCommand($command);
628
629 return $helpCommand;
630 }
631
632 return $command;
633 }
634
635 /**
636 * Returns true if the command exists, false otherwise.
637 */
638 public function has(string $name): bool
639 {
640 $this->init();
641
642 return isset($this->commands[$name]) || ($this->commandLoader?->has($name) && $this->addCommand($this->commandLoader->get($name)));
643 }
644
645 /**
646 * Returns an array of all unique namespaces used by currently registered commands.
647 *
648 * It does not return the global namespace which always exists.
649 *
650 * @return string[]
651 */
652 public function getNamespaces(): array
653 {
654 $namespaces = [];
655 foreach ($this->all() as $command) {
656 if ($command->isHidden()) {
657 continue;
658 }
659
660 $namespaces[] = $this->extractAllNamespaces($command->getName());
661
662 foreach ($command->getAliases() as $alias) {
663 $namespaces[] = $this->extractAllNamespaces($alias);
664 }
665 }
666
667 return array_values(array_unique(array_filter(array_merge([], ...$namespaces))));
668 }
669
670 /**
671 * Finds a registered namespace by a name or an abbreviation.
672 *
673 * @throws NamespaceNotFoundException When namespace is incorrect or ambiguous
674 */
675 public function findNamespace(string $namespace): string
676 {
677 $allNamespaces = $this->getNamespaces();
678 $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $namespace))).'[^:]*';
679 $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
680
681 if (!$namespaces) {
682 $message = \sprintf('There are no commands defined in the "%s" namespace.', $namespace);
683
684 if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
685 if (1 == \count($alternatives)) {
686 $message .= "\n\nDid you mean this?\n ";
687 } else {
688 $message .= "\n\nDid you mean one of these?\n ";
689 }
690
691 $message .= implode("\n ", $alternatives);
692 }
693
694 throw new NamespaceNotFoundException($message, $alternatives);
695 }
696
697 $exact = \in_array($namespace, $namespaces, true);
698 if (\count($namespaces) > 1 && !$exact) {
699 throw new NamespaceNotFoundException(\sprintf("The namespace \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
700 }
701
702 return $exact ? $namespace : reset($namespaces);
703 }
704
705 /**
706 * Finds a command by name or alias.
707 *
708 * Contrary to get, this command tries to find the best
709 * match if you give it an abbreviation of a name or alias.
710 *
711 * @throws CommandNotFoundException When command name is incorrect or ambiguous
712 */
713 public function find(string $name): Command
714 {
715 $this->init();
716
717 $aliases = [];
718
719 foreach ($this->commands as $command) {
720 foreach ($command->getAliases() as $alias) {
721 if (!$this->has($alias)) {
722 $this->commands[$alias] = $command;
723 }
724 }
725 }
726
727 if ($this->has($name)) {
728 return $this->get($name);
729 }
730
731 $allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
732 $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $name))).'[^:]*';
733 $commands = preg_grep('{^'.$expr.'}', $allCommands);
734
735 if (!$commands) {
736 $commands = preg_grep('{^'.$expr.'}i', $allCommands);
737 }
738
739 // if no commands matched or we just matched namespaces
740 if (!$commands || \count(preg_grep('{^'.$expr.'$}i', $commands)) < 1) {
741 if (false !== $pos = strrpos($name, ':')) {
742 // check if a namespace exists and contains commands
743 $this->findNamespace(substr($name, 0, $pos));
744 }
745
746 $message = \sprintf('Command "%s" is not defined.', $name);
747
748 if ($alternatives = $this->findAlternatives($name, $allCommands)) {
749 $wantHelps = $this->wantHelps;
750 $this->wantHelps = false;
751
752 // remove hidden commands
753 if ($alternatives = array_filter($alternatives, fn ($name) => !$this->get($name)->isHidden())) {
754 $message .= \sprintf("\n\nDid you mean %s?\n %s", 1 === \count($alternatives) ? 'this' : 'one of these', implode("\n ", $alternatives));
755 }
756 $this->wantHelps = $wantHelps;
757 }
758
759 throw new CommandNotFoundException($message, array_values($alternatives));
760 }
761
762 // filter out aliases for commands which are already on the list
763 if (\count($commands) > 1) {
764 $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands;
765 $commands = array_unique(array_filter($commands, function ($nameOrAlias) use (&$commandList, $commands, &$aliases) {
766 if (!$commandList[$nameOrAlias] instanceof Command) {
767 $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias);
768 }
769
770 $commandName = $commandList[$nameOrAlias]->getName();
771
772 $aliases[$nameOrAlias] = $commandName;
773
774 return $commandName === $nameOrAlias || !\in_array($commandName, $commands, true);
775 }));
776 }
777
778 // check whether all commands left are aliases to the same one
779 if (\count($commands) > 1) {
780 $uniqueCommands = array_unique(array_map(function ($nameOrAlias) use (&$commandList) {
781 if (!$commandList[$nameOrAlias] instanceof Command) {
782 $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias);
783 }
784
785 return $commandList[$nameOrAlias]->getName();
786 }, $commands));
787
788 if (1 === \count($uniqueCommands)) {
789 $commands = [reset($uniqueCommands)];
790 }
791 }
792
793 if (\count($commands) > 1) {
794 $usableWidth = $this->terminal->getWidth() - 10;
795 $abbrevs = array_values($commands);
796 $maxLen = 0;
797 foreach ($abbrevs as $abbrev) {
798 $maxLen = max(Helper::width($abbrev), $maxLen);
799 }
800 $abbrevs = array_map(static function ($cmd) use ($commandList, $usableWidth, $maxLen, &$commands) {
801 if ($commandList[$cmd]->isHidden()) {
802 unset($commands[array_search($cmd, $commands)]);
803
804 return false;
805 }
806
807 $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription();
808
809 return Helper::width($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev;
810 }, array_values($commands));
811
812 if (\count($commands) > 1) {
813 $suggestions = $this->getAbbreviationSuggestions(array_filter($abbrevs));
814
815 throw new CommandNotFoundException(\sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $name, $suggestions), array_values($commands));
816 }
817 }
818
819 $command = $commands ? $this->get(reset($commands)) : null;
820
821 if (!$command || $command->isHidden()) {
822 throw new CommandNotFoundException(\sprintf('The command "%s" does not exist.', $name));
823 }
824
825 return $command;
826 }
827
828 /**
829 * Gets the commands (registered in the given namespace if provided).
830 *
831 * The array keys are the full names and the values the command instances.
832 *
833 * @return Command[]
834 */
835 public function all(?string $namespace = null): array
836 {
837 $this->init();
838
839 if (null === $namespace) {
840 if (!$this->commandLoader) {
841 return $this->commands;
842 }
843
844 $commands = $this->commands;
845 foreach ($this->commandLoader->getNames() as $name) {
846 if (!isset($commands[$name]) && $this->has($name)) {
847 $commands[$name] = $this->get($name);
848 }
849 }
850
851 return $commands;
852 }
853
854 $commands = [];
855 foreach ($this->commands as $name => $command) {
856 if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
857 $commands[$name] = $command;
858 }
859 }
860
861 if ($this->commandLoader) {
862 foreach ($this->commandLoader->getNames() as $name) {
863 if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) {
864 $commands[$name] = $this->get($name);
865 }
866 }
867 }
868
869 return $commands;
870 }
871
872 /**
873 * Returns an array of possible abbreviations given a set of names.
874 *
875 * @return string[][]
876 */
877 public static function getAbbreviations(array $names): array
878 {
879 $abbrevs = [];
880 foreach ($names as $name) {
881 for ($len = \strlen($name); $len > 0; --$len) {
882 $abbrev = substr($name, 0, $len);
883 $abbrevs[$abbrev][] = $name;
884 }
885 }
886
887 return $abbrevs;
888 }
889
890 public function renderThrowable(\Throwable $e, OutputInterface $output): void
891 {
892 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
893
894 $this->doRenderThrowable($e, $output);
895
896 if (null !== $this->runningCommand) {
897 $output->writeln(\sprintf('<info>%s</info>', OutputFormatter::escape(\sprintf($this->runningCommand->getSynopsis(), $this->getName()))), OutputInterface::VERBOSITY_QUIET);
898 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
899 }
900 }
901
902 protected function doRenderThrowable(\Throwable $e, OutputInterface $output): void
903 {
904 do {
905 $message = trim($e->getMessage());
906 if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
907 $class = get_debug_type($e);
908 $title = \sprintf(' [%s%s] ', $class, 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
909 $len = Helper::width($title);
910 } else {
911 $len = 0;
912 }
913
914 if (str_contains($message, "@anonymous\0")) {
915 $message = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)?[0-9a-fA-F]++/', static fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $message);
916 }
917
918 $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : \PHP_INT_MAX;
919 $lines = [];
920 foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) {
921 foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
922 // pre-format lines to get the right string length
923 $lineLength = Helper::width($line) + 4;
924 $lines[] = [$line, $lineLength];
925
926 $len = max($lineLength, $len);
927 }
928 }
929
930 $messages = [];
931 if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
932 $messages[] = \sprintf('<comment>%s</comment>', OutputFormatter::escape(\sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a')));
933 }
934 $messages[] = $emptyLine = \sprintf('<error>%s</error>', str_repeat(' ', $len));
935 if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
936 $messages[] = \sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::width($title))));
937 }
938 foreach ($lines as $line) {
939 $messages[] = \sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
940 }
941 $messages[] = $emptyLine;
942 $messages[] = '';
943
944 $output->writeln($messages, OutputInterface::VERBOSITY_QUIET);
945
946 if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
947 $output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
948
949 // exception related properties
950 $trace = $e->getTrace();
951
952 array_unshift($trace, [
953 'function' => '',
954 'file' => $e->getFile() ?: 'n/a',
955 'line' => $e->getLine() ?: 'n/a',
956 'args' => [],
957 ]);
958
959 for ($i = 0, $count = \count($trace); $i < $count; ++$i) {
960 $class = $trace[$i]['class'] ?? '';
961 $type = $trace[$i]['type'] ?? '';
962 $function = $trace[$i]['function'] ?? '';
963 $file = $trace[$i]['file'] ?? 'n/a';
964 $line = $trace[$i]['line'] ?? 'n/a';
965
966 $output->writeln(\sprintf(' %s%s at <info>%s:%s</info>', $class, $function ? $type.$function.'()' : '', $file, $line), OutputInterface::VERBOSITY_QUIET);
967 }
968
969 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
970 }
971 } while ($e = $e->getPrevious());
972 }
973
974 /**
975 * Configures the input and output instances based on the user arguments and options.
976 */
977 protected function configureIO(InputInterface $input, OutputInterface $output): void
978 {
979 if ($input->hasParameterOption(['--ansi'], true)) {
980 $output->setDecorated(true);
981 } elseif ($input->hasParameterOption(['--no-ansi'], true)) {
982 $output->setDecorated(false);
983 }
984
985 $shellVerbosity = match (true) {
986 $input->hasParameterOption(['--silent'], true) => -2,
987 $input->hasParameterOption(['--quiet', '-q'], true) => -1,
988 $input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true) => 3,
989 $input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true) => 2,
990 $input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true) => 1,
991 default => (int) ($_ENV['SHELL_VERBOSITY'] ?? $_SERVER['SHELL_VERBOSITY'] ?? getenv('SHELL_VERBOSITY')),
992 };
993
994 $output->setVerbosity(match ($shellVerbosity) {
995 -2 => OutputInterface::VERBOSITY_SILENT,
996 -1 => OutputInterface::VERBOSITY_QUIET,
997 1 => OutputInterface::VERBOSITY_VERBOSE,
998 2 => OutputInterface::VERBOSITY_VERY_VERBOSE,
999 3 => OutputInterface::VERBOSITY_DEBUG,
1000 default => ($shellVerbosity = 0) ?: $output->getVerbosity(),
1001 });
1002
1003 if (0 > $shellVerbosity || $input->hasParameterOption(['--no-interaction', '-n'], true)) {
1004 $input->setInteractive(false);
1005 }
1006
1007 if (\function_exists('putenv')) {
1008 @putenv('SHELL_VERBOSITY='.$shellVerbosity);
1009 }
1010 $_ENV['SHELL_VERBOSITY'] = $shellVerbosity;
1011 $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity;
1012 }
1013
1014 /**
1015 * Runs the current command.
1016 *
1017 * If an event dispatcher has been attached to the application,
1018 * events are also dispatched during the life-cycle of the command.
1019 *
1020 * @return int 0 if everything went fine, or an error code
1021 */
1022 protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output): int
1023 {
1024 foreach ($command->getHelperSet() as $helper) {
1025 if ($helper instanceof InputAwareInterface) {
1026 $helper->setInput($input);
1027 }
1028 }
1029
1030 $registeredSignals = false;
1031 if (($commandSignals = $command->getSubscribedSignals()) || $this->dispatcher && $this->signalsToDispatchEvent) {
1032 $signalRegistry = $this->getSignalRegistry();
1033
1034 $registeredSignals = true;
1035 $this->getSignalRegistry()->pushCurrentHandlers();
1036
1037 if ($this->dispatcher) {
1038 // We register application signals, so that we can dispatch the event
1039 foreach ($this->signalsToDispatchEvent as $signal) {
1040 $signalEvent = new ConsoleSignalEvent($command, $input, $output, $signal);
1041 $alarmEvent = \SIGALRM === $signal ? new ConsoleAlarmEvent($command, $input, $output) : null;
1042
1043 $signalRegistry->register($signal, function ($signal) use ($signalEvent, $alarmEvent, $command, $commandSignals, $input, $output) {
1044 $this->dispatcher->dispatch($signalEvent, ConsoleEvents::SIGNAL);
1045 $exitCode = $signalEvent->getExitCode();
1046
1047 if (null !== $alarmEvent) {
1048 if (false !== $exitCode) {
1049 $alarmEvent->setExitCode($exitCode);
1050 } else {
1051 $alarmEvent->abortExit();
1052 }
1053 $this->dispatcher->dispatch($alarmEvent);
1054 $exitCode = $alarmEvent->getExitCode();
1055 }
1056
1057 // If the command is signalable, we call the handleSignal() method
1058 if (\in_array($signal, $commandSignals, true)) {
1059 $exitCode = $command->handleSignal($signal, $exitCode);
1060 }
1061
1062 if (\SIGALRM === $signal) {
1063 $this->scheduleAlarm();
1064 }
1065
1066 if (false !== $exitCode) {
1067 $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode, $signal);
1068 $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
1069
1070 exit($event->getExitCode());
1071 }
1072 });
1073 }
1074
1075 // then we register command signals, but not if already handled after the dispatcher
1076 $commandSignals = array_diff($commandSignals, $this->signalsToDispatchEvent);
1077 }
1078
1079 foreach ($commandSignals as $signal) {
1080 $signalRegistry->register($signal, function (int $signal) use ($command): void {
1081 if (\SIGALRM === $signal) {
1082 $this->scheduleAlarm();
1083 }
1084
1085 if (false !== $exitCode = $command->handleSignal($signal)) {
1086 exit($exitCode);
1087 }
1088 });
1089 }
1090 }
1091
1092 if (null === $this->dispatcher) {
1093 try {
1094 return $command->run($input, $output);
1095 } finally {
1096 if ($registeredSignals) {
1097 $this->getSignalRegistry()->popPreviousHandlers();
1098 }
1099 }
1100 }
1101
1102 // bind before the console.command event, so the listeners have access to input options/arguments
1103 try {
1104 $command->mergeApplicationDefinition();
1105 $input->bind($command->getDefinition());
1106 } catch (ExceptionInterface) {
1107 // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
1108 }
1109
1110 $event = new ConsoleCommandEvent($command, $input, $output);
1111 $e = null;
1112
1113 try {
1114 $this->dispatcher->dispatch($event, ConsoleEvents::COMMAND);
1115
1116 if ($event->commandShouldRun()) {
1117 $exitCode = $command->run($input, $output);
1118 } else {
1119 $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
1120 }
1121 } catch (\Throwable $e) {
1122 $event = new ConsoleErrorEvent($input, $output, $e, $command);
1123 $this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
1124 $e = $event->getError();
1125
1126 if (0 === $exitCode = $event->getExitCode()) {
1127 $e = null;
1128 }
1129 } finally {
1130 if ($registeredSignals) {
1131 $this->getSignalRegistry()->popPreviousHandlers();
1132 }
1133 }
1134
1135 $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
1136 $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
1137
1138 if (null !== $e) {
1139 throw $e;
1140 }
1141
1142 return $event->getExitCode();
1143 }
1144
1145 /**
1146 * Gets the name of the command based on input.
1147 */
1148 protected function getCommandName(InputInterface $input): ?string
1149 {
1150 return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument();
1151 }
1152
1153 /**
1154 * Gets the default input definition.
1155 */
1156 protected function getDefaultInputDefinition(): InputDefinition
1157 {
1158 return new InputDefinition([
1159 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
1160 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display help for the given command. When no command is given display help for the <info>'.$this->defaultCommand.'</info> command'),
1161 new InputOption('--silent', null, InputOption::VALUE_NONE, 'Do not output any message'),
1162 new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Only errors are displayed. All other output is suppressed'),
1163 new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'),
1164 new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
1165 new InputOption('--ansi', '', InputOption::VALUE_NEGATABLE, 'Force (or disable --no-ansi) ANSI output', null),
1166 new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
1167 ]);
1168 }
1169
1170 /**
1171 * Gets the default commands that should always be available.
1172 *
1173 * @return Command[]
1174 */
1175 protected function getDefaultCommands(): array
1176 {
1177 return [new HelpCommand(), new ListCommand(), new CompleteCommand(), new DumpCompletionCommand()];
1178 }
1179
1180 /**
1181 * Gets the default helper set with the helpers that should always be available.
1182 */
1183 protected function getDefaultHelperSet(): HelperSet
1184 {
1185 return new HelperSet([
1186 new FormatterHelper(),
1187 new DebugFormatterHelper(),
1188 new ProcessHelper(),
1189 new QuestionHelper(),
1190 ]);
1191 }
1192
1193 /**
1194 * Returns abbreviated suggestions in string format.
1195 */
1196 private function getAbbreviationSuggestions(array $abbrevs): string
1197 {
1198 return ' '.implode("\n ", $abbrevs);
1199 }
1200
1201 /**
1202 * Returns the namespace part of the command name.
1203 *
1204 * This method is not part of public API and should not be used directly.
1205 */
1206 public function extractNamespace(string $name, ?int $limit = null): string
1207 {
1208 $parts = explode(':', $name, -1);
1209
1210 return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit));
1211 }
1212
1213 /**
1214 * Finds alternative of $name among $collection,
1215 * if nothing is found in $collection, try in $abbrevs.
1216 *
1217 * @return string[]
1218 */
1219 private function findAlternatives(string $name, iterable $collection): array
1220 {
1221 $threshold = 1e3;
1222 $alternatives = [];
1223
1224 $collectionParts = [];
1225 foreach ($collection as $item) {
1226 $collectionParts[$item] = explode(':', $item);
1227 }
1228
1229 foreach (explode(':', $name) as $i => $subname) {
1230 foreach ($collectionParts as $collectionName => $parts) {
1231 $exists = isset($alternatives[$collectionName]);
1232 if (!isset($parts[$i]) && $exists) {
1233 $alternatives[$collectionName] += $threshold;
1234 continue;
1235 } elseif (!isset($parts[$i])) {
1236 continue;
1237 }
1238
1239 $lev = levenshtein($subname, $parts[$i]);
1240 if ($lev <= \strlen($subname) / 3 || '' !== $subname && str_contains($parts[$i], $subname)) {
1241 $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
1242 } elseif ($exists) {
1243 $alternatives[$collectionName] += $threshold;
1244 }
1245 }
1246 }
1247
1248 foreach ($collection as $item) {
1249 $lev = levenshtein($name, $item);
1250 if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) {
1251 $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
1252 }
1253 }
1254
1255 $alternatives = array_filter($alternatives, static fn ($lev) => $lev < 2 * $threshold);
1256 ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE);
1257
1258 return array_keys($alternatives);
1259 }
1260
1261 /**
1262 * Sets the default Command name.
1263 *
1264 * @return $this
1265 */
1266 public function setDefaultCommand(string $commandName, bool $isSingleCommand = false): static
1267 {
1268 $this->defaultCommand = explode('|', ltrim($commandName, '|'))[0];
1269
1270 if ($isSingleCommand) {
1271 // Ensure the command exist
1272 $this->find($commandName);
1273
1274 $this->singleCommand = true;
1275 }
1276
1277 return $this;
1278 }
1279
1280 /**
1281 * @internal
1282 */
1283 public function isSingleCommand(): bool
1284 {
1285 return $this->singleCommand;
1286 }
1287
1288 private function splitStringByWidth(string $string, int $width): array
1289 {
1290 // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
1291 // additionally, array_slice() is not enough as some character has doubled width.
1292 // we need a function to split string not by character count but by string width
1293 if (false === $encoding = mb_detect_encoding($string, null, true)) {
1294 return str_split($string, $width);
1295 }
1296
1297 $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
1298 $lines = [];
1299 $line = '';
1300
1301 $offset = 0;
1302 while (preg_match('/.{1,10000}/u', $utf8String, $m, 0, $offset)) {
1303 $offset += \strlen($m[0]);
1304
1305 foreach (preg_split('//u', $m[0]) as $char) {
1306 // test if $char could be appended to current line
1307 if (Helper::width($line.$char) <= $width) {
1308 $line .= $char;
1309 continue;
1310 }
1311 // if not, push current line to array and make new line
1312 $lines[] = str_pad($line, $width);
1313 $line = $char;
1314 }
1315 }
1316
1317 $lines[] = \count($lines) ? str_pad($line, $width) : $line;
1318
1319 return mb_convert_encoding($lines, $encoding, 'utf8');
1320 }
1321
1322 /**
1323 * Returns all namespaces of the command name.
1324 *
1325 * @return string[]
1326 */
1327 private function extractAllNamespaces(string $name): array
1328 {
1329 // -1 as third argument is needed to skip the command short name when exploding
1330 $parts = explode(':', $name, -1);
1331 $namespaces = [];
1332
1333 foreach ($parts as $part) {
1334 if (\count($namespaces)) {
1335 $namespaces[] = end($namespaces).':'.$part;
1336 } else {
1337 $namespaces[] = $part;
1338 }
1339 }
1340
1341 return $namespaces;
1342 }
1343
1344 private function init(): void
1345 {
1346 if ($this->initialized) {
1347 return;
1348 }
1349 $this->initialized = true;
1350
1351 if ((new \ReflectionMethod($this, 'add'))->getDeclaringClass()->getName() !== (new \ReflectionMethod($this, 'addCommand'))->getDeclaringClass()->getName()) {
1352 $adder = $this->add(...);
1353 } else {
1354 $adder = $this->addCommand(...);
1355 }
1356
1357 foreach ($this->getDefaultCommands() as $command) {
1358 $adder($command);
1359 }
1360 }
1361 }