vendor/symfony/console/Application.php line 139

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