vendor/symfony/console/Application.php line 1081

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