vendor/symfony/console/Application.php line 1138

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 $commands = [];
  70.     private $wantHelps false;
  71.     private $runningCommand;
  72.     private $name;
  73.     private $version;
  74.     private $commandLoader;
  75.     private $catchExceptions true;
  76.     private $autoExit true;
  77.     private $definition;
  78.     private $helperSet;
  79.     private $dispatcher;
  80.     private $terminal;
  81.     private $defaultCommand;
  82.     private $singleCommand false;
  83.     private $initialized;
  84.     private $signalRegistry;
  85.     private $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 nullOutputInterface $output null)
  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 ($exitCode <= 0) {
  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 $inputOutputInterface $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) || !== \count($alternatives $e->getAlternatives()) || !$input->isInteractive()) {
  235.                 if (null !== $this->dispatcher) {
  236.                     $event = new ConsoleErrorEvent($input$output$e);
  237.                     $this->dispatcher->dispatch($eventConsoleEvents::ERROR);
  238.                     if (=== $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($eventConsoleEvents::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.      * @return HelperSet
  280.      */
  281.     public function getHelperSet()
  282.     {
  283.         if (!$this->helperSet) {
  284.             $this->helperSet $this->getDefaultHelperSet();
  285.         }
  286.         return $this->helperSet;
  287.     }
  288.     public function setDefinition(InputDefinition $definition)
  289.     {
  290.         $this->definition $definition;
  291.     }
  292.     /**
  293.      * Gets the InputDefinition related to this Application.
  294.      *
  295.      * @return InputDefinition
  296.      */
  297.     public function getDefinition()
  298.     {
  299.         if (!$this->definition) {
  300.             $this->definition $this->getDefaultInputDefinition();
  301.         }
  302.         if ($this->singleCommand) {
  303.             $inputDefinition $this->definition;
  304.             $inputDefinition->setArguments();
  305.             return $inputDefinition;
  306.         }
  307.         return $this->definition;
  308.     }
  309.     /**
  310.      * Adds suggestions to $suggestions for the current completion input (e.g. option or argument).
  311.      */
  312.     public function complete(CompletionInput $inputCompletionSuggestions $suggestions): void
  313.     {
  314.         if (
  315.             CompletionInput::TYPE_ARGUMENT_VALUE === $input->getCompletionType()
  316.             && 'command' === $input->getCompletionName()
  317.         ) {
  318.             $commandNames = [];
  319.             foreach ($this->all() as $name => $command) {
  320.                 // skip hidden commands and aliased commands as they already get added below
  321.                 if ($command->isHidden() || $command->getName() !== $name) {
  322.                     continue;
  323.                 }
  324.                 $commandNames[] = $command->getName();
  325.                 foreach ($command->getAliases() as $name) {
  326.                     $commandNames[] = $name;
  327.                 }
  328.             }
  329.             $suggestions->suggestValues(array_filter($commandNames));
  330.             return;
  331.         }
  332.         if (CompletionInput::TYPE_OPTION_NAME === $input->getCompletionType()) {
  333.             $suggestions->suggestOptions($this->getDefinition()->getOptions());
  334.             return;
  335.         }
  336.     }
  337.     /**
  338.      * Gets the help message.
  339.      *
  340.      * @return string
  341.      */
  342.     public function getHelp()
  343.     {
  344.         return $this->getLongVersion();
  345.     }
  346.     /**
  347.      * Gets whether to catch exceptions or not during commands execution.
  348.      *
  349.      * @return bool
  350.      */
  351.     public function areExceptionsCaught()
  352.     {
  353.         return $this->catchExceptions;
  354.     }
  355.     /**
  356.      * Sets whether to catch exceptions or not during commands execution.
  357.      */
  358.     public function setCatchExceptions(bool $boolean)
  359.     {
  360.         $this->catchExceptions $boolean;
  361.     }
  362.     /**
  363.      * Gets whether to automatically exit after a command execution or not.
  364.      *
  365.      * @return bool
  366.      */
  367.     public function isAutoExitEnabled()
  368.     {
  369.         return $this->autoExit;
  370.     }
  371.     /**
  372.      * Sets whether to automatically exit after a command execution or not.
  373.      */
  374.     public function setAutoExit(bool $boolean)
  375.     {
  376.         $this->autoExit $boolean;
  377.     }
  378.     /**
  379.      * Gets the name of the application.
  380.      *
  381.      * @return string
  382.      */
  383.     public function getName()
  384.     {
  385.         return $this->name;
  386.     }
  387.     /**
  388.      * Sets the application name.
  389.      **/
  390.     public function setName(string $name)
  391.     {
  392.         $this->name $name;
  393.     }
  394.     /**
  395.      * Gets the application version.
  396.      *
  397.      * @return string
  398.      */
  399.     public function getVersion()
  400.     {
  401.         return $this->version;
  402.     }
  403.     /**
  404.      * Sets the application version.
  405.      */
  406.     public function setVersion(string $version)
  407.     {
  408.         $this->version $version;
  409.     }
  410.     /**
  411.      * Returns the long version of the application.
  412.      *
  413.      * @return string
  414.      */
  415.     public function getLongVersion()
  416.     {
  417.         if ('UNKNOWN' !== $this->getName()) {
  418.             if ('UNKNOWN' !== $this->getVersion()) {
  419.                 return sprintf('%s <info>%s</info>'$this->getName(), $this->getVersion());
  420.             }
  421.             return $this->getName();
  422.         }
  423.         return 'Console Tool';
  424.     }
  425.     /**
  426.      * Registers a new command.
  427.      *
  428.      * @return Command
  429.      */
  430.     public function register(string $name)
  431.     {
  432.         return $this->add(new Command($name));
  433.     }
  434.     /**
  435.      * Adds an array of command objects.
  436.      *
  437.      * If a Command is not enabled it will not be added.
  438.      *
  439.      * @param Command[] $commands An array of commands
  440.      */
  441.     public function addCommands(array $commands)
  442.     {
  443.         foreach ($commands as $command) {
  444.             $this->add($command);
  445.         }
  446.     }
  447.     /**
  448.      * Adds a command object.
  449.      *
  450.      * If a command with the same name already exists, it will be overridden.
  451.      * If the command is not enabled it will not be added.
  452.      *
  453.      * @return Command|null
  454.      */
  455.     public function add(Command $command)
  456.     {
  457.         $this->init();
  458.         $command->setApplication($this);
  459.         if (!$command->isEnabled()) {
  460.             $command->setApplication(null);
  461.             return null;
  462.         }
  463.         if (!$command instanceof LazyCommand) {
  464.             // Will throw if the command is not correctly initialized.
  465.             $command->getDefinition();
  466.         }
  467.         if (!$command->getName()) {
  468.             throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.'get_debug_type($command)));
  469.         }
  470.         $this->commands[$command->getName()] = $command;
  471.         foreach ($command->getAliases() as $alias) {
  472.             $this->commands[$alias] = $command;
  473.         }
  474.         return $command;
  475.     }
  476.     /**
  477.      * Returns a registered command by name or alias.
  478.      *
  479.      * @return Command
  480.      *
  481.      * @throws CommandNotFoundException When given command name does not exist
  482.      */
  483.     public function get(string $name)
  484.     {
  485.         $this->init();
  486.         if (!$this->has($name)) {
  487.             throw new CommandNotFoundException(sprintf('The command "%s" does not exist.'$name));
  488.         }
  489.         // When the command has a different name than the one used at the command loader level
  490.         if (!isset($this->commands[$name])) {
  491.             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));
  492.         }
  493.         $command $this->commands[$name];
  494.         if ($this->wantHelps) {
  495.             $this->wantHelps false;
  496.             $helpCommand $this->get('help');
  497.             $helpCommand->setCommand($command);
  498.             return $helpCommand;
  499.         }
  500.         return $command;
  501.     }
  502.     /**
  503.      * Returns true if the command exists, false otherwise.
  504.      *
  505.      * @return bool
  506.      */
  507.     public function has(string $name)
  508.     {
  509.         $this->init();
  510.         return isset($this->commands[$name]) || ($this->commandLoader && $this->commandLoader->has($name) && $this->add($this->commandLoader->get($name)));
  511.     }
  512.     /**
  513.      * Returns an array of all unique namespaces used by currently registered commands.
  514.      *
  515.      * It does not return the global namespace which always exists.
  516.      *
  517.      * @return string[]
  518.      */
  519.     public function getNamespaces()
  520.     {
  521.         $namespaces = [];
  522.         foreach ($this->all() as $command) {
  523.             if ($command->isHidden()) {
  524.                 continue;
  525.             }
  526.             $namespaces[] = $this->extractAllNamespaces($command->getName());
  527.             foreach ($command->getAliases() as $alias) {
  528.                 $namespaces[] = $this->extractAllNamespaces($alias);
  529.             }
  530.         }
  531.         return array_values(array_unique(array_filter(array_merge([], ...$namespaces))));
  532.     }
  533.     /**
  534.      * Finds a registered namespace by a name or an abbreviation.
  535.      *
  536.      * @return string
  537.      *
  538.      * @throws NamespaceNotFoundException When namespace is incorrect or ambiguous
  539.      */
  540.     public function findNamespace(string $namespace)
  541.     {
  542.         $allNamespaces $this->getNamespaces();
  543.         $expr implode('[^:]*:'array_map('preg_quote'explode(':'$namespace))).'[^:]*';
  544.         $namespaces preg_grep('{^'.$expr.'}'$allNamespaces);
  545.         if (empty($namespaces)) {
  546.             $message sprintf('There are no commands defined in the "%s" namespace.'$namespace);
  547.             if ($alternatives $this->findAlternatives($namespace$allNamespaces)) {
  548.                 if (== \count($alternatives)) {
  549.                     $message .= "\n\nDid you mean this?\n    ";
  550.                 } else {
  551.                     $message .= "\n\nDid you mean one of these?\n    ";
  552.                 }
  553.                 $message .= implode("\n    "$alternatives);
  554.             }
  555.             throw new NamespaceNotFoundException($message$alternatives);
  556.         }
  557.         $exact \in_array($namespace$namespacestrue);
  558.         if (\count($namespaces) > && !$exact) {
  559.             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));
  560.         }
  561.         return $exact $namespace reset($namespaces);
  562.     }
  563.     /**
  564.      * Finds a command by name or alias.
  565.      *
  566.      * Contrary to get, this command tries to find the best
  567.      * match if you give it an abbreviation of a name or alias.
  568.      *
  569.      * @return Command
  570.      *
  571.      * @throws CommandNotFoundException When command name is incorrect or ambiguous
  572.      */
  573.     public function find(string $name)
  574.     {
  575.         $this->init();
  576.         $aliases = [];
  577.         foreach ($this->commands as $command) {
  578.             foreach ($command->getAliases() as $alias) {
  579.                 if (!$this->has($alias)) {
  580.                     $this->commands[$alias] = $command;
  581.                 }
  582.             }
  583.         }
  584.         if ($this->has($name)) {
  585.             return $this->get($name);
  586.         }
  587.         $allCommands $this->commandLoader array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
  588.         $expr implode('[^:]*:'array_map('preg_quote'explode(':'$name))).'[^:]*';
  589.         $commands preg_grep('{^'.$expr.'}'$allCommands);
  590.         if (empty($commands)) {
  591.             $commands preg_grep('{^'.$expr.'}i'$allCommands);
  592.         }
  593.         // if no commands matched or we just matched namespaces
  594.         if (empty($commands) || \count(preg_grep('{^'.$expr.'$}i'$commands)) < 1) {
  595.             if (false !== $pos strrpos($name':')) {
  596.                 // check if a namespace exists and contains commands
  597.                 $this->findNamespace(substr($name0$pos));
  598.             }
  599.             $message sprintf('Command "%s" is not defined.'$name);
  600.             if ($alternatives $this->findAlternatives($name$allCommands)) {
  601.                 // remove hidden commands
  602.                 $alternatives array_filter($alternatives, function ($name) {
  603.                     return !$this->get($name)->isHidden();
  604.                 });
  605.                 if (== \count($alternatives)) {
  606.                     $message .= "\n\nDid you mean this?\n    ";
  607.                 } else {
  608.                     $message .= "\n\nDid you mean one of these?\n    ";
  609.                 }
  610.                 $message .= implode("\n    "$alternatives);
  611.             }
  612.             throw new CommandNotFoundException($messagearray_values($alternatives));
  613.         }
  614.         // filter out aliases for commands which are already on the list
  615.         if (\count($commands) > 1) {
  616.             $commandList $this->commandLoader array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands;
  617.             $commands array_unique(array_filter($commands, function ($nameOrAlias) use (&$commandList$commands, &$aliases) {
  618.                 if (!$commandList[$nameOrAlias] instanceof Command) {
  619.                     $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias);
  620.                 }
  621.                 $commandName $commandList[$nameOrAlias]->getName();
  622.                 $aliases[$nameOrAlias] = $commandName;
  623.                 return $commandName === $nameOrAlias || !\in_array($commandName$commands);
  624.             }));
  625.         }
  626.         if (\count($commands) > 1) {
  627.             $usableWidth $this->terminal->getWidth() - 10;
  628.             $abbrevs array_values($commands);
  629.             $maxLen 0;
  630.             foreach ($abbrevs as $abbrev) {
  631.                 $maxLen max(Helper::width($abbrev), $maxLen);
  632.             }
  633.             $abbrevs array_map(function ($cmd) use ($commandList$usableWidth$maxLen, &$commands) {
  634.                 if ($commandList[$cmd]->isHidden()) {
  635.                     unset($commands[array_search($cmd$commands)]);
  636.                     return false;
  637.                 }
  638.                 $abbrev str_pad($cmd$maxLen' ').' '.$commandList[$cmd]->getDescription();
  639.                 return Helper::width($abbrev) > $usableWidth Helper::substr($abbrev0$usableWidth 3).'...' $abbrev;
  640.             }, array_values($commands));
  641.             if (\count($commands) > 1) {
  642.                 $suggestions $this->getAbbreviationSuggestions(array_filter($abbrevs));
  643.                 throw new CommandNotFoundException(sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s."$name$suggestions), array_values($commands));
  644.             }
  645.         }
  646.         $command $this->get(reset($commands));
  647.         if ($command->isHidden()) {
  648.             throw new CommandNotFoundException(sprintf('The command "%s" does not exist.'$name));
  649.         }
  650.         return $command;
  651.     }
  652.     /**
  653.      * Gets the commands (registered in the given namespace if provided).
  654.      *
  655.      * The array keys are the full names and the values the command instances.
  656.      *
  657.      * @return Command[]
  658.      */
  659.     public function all(string $namespace null)
  660.     {
  661.         $this->init();
  662.         if (null === $namespace) {
  663.             if (!$this->commandLoader) {
  664.                 return $this->commands;
  665.             }
  666.             $commands $this->commands;
  667.             foreach ($this->commandLoader->getNames() as $name) {
  668.                 if (!isset($commands[$name]) && $this->has($name)) {
  669.                     $commands[$name] = $this->get($name);
  670.                 }
  671.             }
  672.             return $commands;
  673.         }
  674.         $commands = [];
  675.         foreach ($this->commands as $name => $command) {
  676.             if ($namespace === $this->extractNamespace($namesubstr_count($namespace':') + 1)) {
  677.                 $commands[$name] = $command;
  678.             }
  679.         }
  680.         if ($this->commandLoader) {
  681.             foreach ($this->commandLoader->getNames() as $name) {
  682.                 if (!isset($commands[$name]) && $namespace === $this->extractNamespace($namesubstr_count($namespace':') + 1) && $this->has($name)) {
  683.                     $commands[$name] = $this->get($name);
  684.                 }
  685.             }
  686.         }
  687.         return $commands;
  688.     }
  689.     /**
  690.      * Returns an array of possible abbreviations given a set of names.
  691.      *
  692.      * @return string[][]
  693.      */
  694.     public static function getAbbreviations(array $names)
  695.     {
  696.         $abbrevs = [];
  697.         foreach ($names as $name) {
  698.             for ($len \strlen($name); $len 0; --$len) {
  699.                 $abbrev substr($name0$len);
  700.                 $abbrevs[$abbrev][] = $name;
  701.             }
  702.         }
  703.         return $abbrevs;
  704.     }
  705.     public function renderThrowable(\Throwable $eOutputInterface $output): void
  706.     {
  707.         $output->writeln(''OutputInterface::VERBOSITY_QUIET);
  708.         $this->doRenderThrowable($e$output);
  709.         if (null !== $this->runningCommand) {
  710.             $output->writeln(sprintf('<info>%s</info>'OutputFormatter::escape(sprintf($this->runningCommand->getSynopsis(), $this->getName()))), OutputInterface::VERBOSITY_QUIET);
  711.             $output->writeln(''OutputInterface::VERBOSITY_QUIET);
  712.         }
  713.     }
  714.     protected function doRenderThrowable(\Throwable $eOutputInterface $output): void
  715.     {
  716.         do {
  717.             $message trim($e->getMessage());
  718.             if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  719.                 $class get_debug_type($e);
  720.                 $title sprintf('  [%s%s]  '$class!== ($code $e->getCode()) ? ' ('.$code.')' '');
  721.                 $len Helper::width($title);
  722.             } else {
  723.                 $len 0;
  724.             }
  725.             if (str_contains($message"@anonymous\0")) {
  726.                 $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) {
  727.                     return class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' $m[0];
  728.                 }, $message);
  729.             }
  730.             $width $this->terminal->getWidth() ? $this->terminal->getWidth() - \PHP_INT_MAX;
  731.             $lines = [];
  732.             foreach ('' !== $message preg_split('/\r?\n/'$message) : [] as $line) {
  733.                 foreach ($this->splitStringByWidth($line$width 4) as $line) {
  734.                     // pre-format lines to get the right string length
  735.                     $lineLength Helper::width($line) + 4;
  736.                     $lines[] = [$line$lineLength];
  737.                     $len max($lineLength$len);
  738.                 }
  739.             }
  740.             $messages = [];
  741.             if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  742.                 $messages[] = sprintf('<comment>%s</comment>'OutputFormatter::escape(sprintf('In %s line %s:'basename($e->getFile()) ?: 'n/a'$e->getLine() ?: 'n/a')));
  743.             }
  744.             $messages[] = $emptyLine sprintf('<error>%s</error>'str_repeat(' '$len));
  745.             if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  746.                 $messages[] = sprintf('<error>%s%s</error>'$titlestr_repeat(' 'max(0$len Helper::width($title))));
  747.             }
  748.             foreach ($lines as $line) {
  749.                 $messages[] = sprintf('<error>  %s  %s</error>'OutputFormatter::escape($line[0]), str_repeat(' '$len $line[1]));
  750.             }
  751.             $messages[] = $emptyLine;
  752.             $messages[] = '';
  753.             $output->writeln($messagesOutputInterface::VERBOSITY_QUIET);
  754.             if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  755.                 $output->writeln('<comment>Exception trace:</comment>'OutputInterface::VERBOSITY_QUIET);
  756.                 // exception related properties
  757.                 $trace $e->getTrace();
  758.                 array_unshift($trace, [
  759.                     'function' => '',
  760.                     'file' => $e->getFile() ?: 'n/a',
  761.                     'line' => $e->getLine() ?: 'n/a',
  762.                     'args' => [],
  763.                 ]);
  764.                 for ($i 0$count \count($trace); $i $count; ++$i) {
  765.                     $class $trace[$i]['class'] ?? '';
  766.                     $type $trace[$i]['type'] ?? '';
  767.                     $function $trace[$i]['function'] ?? '';
  768.                     $file $trace[$i]['file'] ?? 'n/a';
  769.                     $line $trace[$i]['line'] ?? 'n/a';
  770.                     $output->writeln(sprintf(' %s%s at <info>%s:%s</info>'$class$function $type.$function.'()' ''$file$line), OutputInterface::VERBOSITY_QUIET);
  771.                 }
  772.                 $output->writeln(''OutputInterface::VERBOSITY_QUIET);
  773.             }
  774.         } while ($e $e->getPrevious());
  775.     }
  776.     /**
  777.      * Configures the input and output instances based on the user arguments and options.
  778.      */
  779.     protected function configureIO(InputInterface $inputOutputInterface $output)
  780.     {
  781.         if (true === $input->hasParameterOption(['--ansi'], true)) {
  782.             $output->setDecorated(true);
  783.         } elseif (true === $input->hasParameterOption(['--no-ansi'], true)) {
  784.             $output->setDecorated(false);
  785.         }
  786.         if (true === $input->hasParameterOption(['--no-interaction''-n'], true)) {
  787.             $input->setInteractive(false);
  788.         }
  789.         switch ($shellVerbosity = (int) getenv('SHELL_VERBOSITY')) {
  790.             case -1$output->setVerbosity(OutputInterface::VERBOSITY_QUIET); break;
  791.             case 1$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); break;
  792.             case 2$output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); break;
  793.             case 3$output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); break;
  794.             default: $shellVerbosity 0; break;
  795.         }
  796.         if (true === $input->hasParameterOption(['--quiet''-q'], true)) {
  797.             $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
  798.             $shellVerbosity = -1;
  799.         } else {
  800.             if ($input->hasParameterOption('-vvv'true) || $input->hasParameterOption('--verbose=3'true) || === $input->getParameterOption('--verbose'falsetrue)) {
  801.                 $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
  802.                 $shellVerbosity 3;
  803.             } elseif ($input->hasParameterOption('-vv'true) || $input->hasParameterOption('--verbose=2'true) || === $input->getParameterOption('--verbose'falsetrue)) {
  804.                 $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
  805.                 $shellVerbosity 2;
  806.             } elseif ($input->hasParameterOption('-v'true) || $input->hasParameterOption('--verbose=1'true) || $input->hasParameterOption('--verbose'true) || $input->getParameterOption('--verbose'falsetrue)) {
  807.                 $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
  808.                 $shellVerbosity 1;
  809.             }
  810.         }
  811.         if (-=== $shellVerbosity) {
  812.             $input->setInteractive(false);
  813.         }
  814.         if (\function_exists('putenv')) {
  815.             @putenv('SHELL_VERBOSITY='.$shellVerbosity);
  816.         }
  817.         $_ENV['SHELL_VERBOSITY'] = $shellVerbosity;
  818.         $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity;
  819.     }
  820.     /**
  821.      * Runs the current command.
  822.      *
  823.      * If an event dispatcher has been attached to the application,
  824.      * events are also dispatched during the life-cycle of the command.
  825.      *
  826.      * @return int 0 if everything went fine, or an error code
  827.      */
  828.     protected function doRunCommand(Command $commandInputInterface $inputOutputInterface $output)
  829.     {
  830.         foreach ($command->getHelperSet() as $helper) {
  831.             if ($helper instanceof InputAwareInterface) {
  832.                 $helper->setInput($input);
  833.             }
  834.         }
  835.         if ($this->signalsToDispatchEvent) {
  836.             $commandSignals $command instanceof SignalableCommandInterface $command->getSubscribedSignals() : [];
  837.             if ($commandSignals || null !== $this->dispatcher) {
  838.                 if (!$this->signalRegistry) {
  839.                     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.');
  840.                 }
  841.                 if (Terminal::hasSttyAvailable()) {
  842.                     $sttyMode shell_exec('stty -g');
  843.                     foreach ([\SIGINT\SIGTERM] as $signal) {
  844.                         $this->signalRegistry->register($signal, static function () use ($sttyMode) {
  845.                             shell_exec('stty '.$sttyMode);
  846.                         });
  847.                     }
  848.                 }
  849.                 foreach ($commandSignals as $signal) {
  850.                     $this->signalRegistry->register($signal, [$command'handleSignal']);
  851.                 }
  852.             }
  853.             if (null !== $this->dispatcher) {
  854.                 foreach ($this->signalsToDispatchEvent as $signal) {
  855.                     $event = new ConsoleSignalEvent($command$input$output$signal);
  856.                     $this->signalRegistry->register($signal, function ($signal$hasNext) use ($event) {
  857.                         $this->dispatcher->dispatch($eventConsoleEvents::SIGNAL);
  858.                         // No more handlers, we try to simulate PHP default behavior
  859.                         if (!$hasNext) {
  860.                             if (!\in_array($signal, [\SIGUSR1\SIGUSR2], true)) {
  861.                                 exit(0);
  862.                             }
  863.                         }
  864.                     });
  865.                 }
  866.             }
  867.         }
  868.         if (null === $this->dispatcher) {
  869.             return $command->run($input$output);
  870.         }
  871.         // bind before the console.command event, so the listeners have access to input options/arguments
  872.         try {
  873.             $command->mergeApplicationDefinition();
  874.             $input->bind($command->getDefinition());
  875.         } catch (ExceptionInterface $e) {
  876.             // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
  877.         }
  878.         $event = new ConsoleCommandEvent($command$input$output);
  879.         $e null;
  880.         try {
  881.             $this->dispatcher->dispatch($eventConsoleEvents::COMMAND);
  882.             if ($event->commandShouldRun()) {
  883.                 $exitCode $command->run($input$output);
  884.             } else {
  885.                 $exitCode ConsoleCommandEvent::RETURN_CODE_DISABLED;
  886.             }
  887.         } catch (\Throwable $e) {
  888.             $event = new ConsoleErrorEvent($input$output$e$command);
  889.             $this->dispatcher->dispatch($eventConsoleEvents::ERROR);
  890.             $e $event->getError();
  891.             if (=== $exitCode $event->getExitCode()) {
  892.                 $e null;
  893.             }
  894.         }
  895.         $event = new ConsoleTerminateEvent($command$input$output$exitCode);
  896.         $this->dispatcher->dispatch($eventConsoleEvents::TERMINATE);
  897.         if (null !== $e) {
  898.             throw $e;
  899.         }
  900.         return $event->getExitCode();
  901.     }
  902.     /**
  903.      * Gets the name of the command based on input.
  904.      *
  905.      * @return string|null
  906.      */
  907.     protected function getCommandName(InputInterface $input)
  908.     {
  909.         return $this->singleCommand $this->defaultCommand $input->getFirstArgument();
  910.     }
  911.     /**
  912.      * Gets the default input definition.
  913.      *
  914.      * @return InputDefinition
  915.      */
  916.     protected function getDefaultInputDefinition()
  917.     {
  918.         return new InputDefinition([
  919.             new InputArgument('command'InputArgument::REQUIRED'The command to execute'),
  920.             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'),
  921.             new InputOption('--quiet''-q'InputOption::VALUE_NONE'Do not output any message'),
  922.             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'),
  923.             new InputOption('--version''-V'InputOption::VALUE_NONE'Display this application version'),
  924.             new InputOption('--ansi'''InputOption::VALUE_NEGATABLE'Force (or disable --no-ansi) ANSI output'null),
  925.             new InputOption('--no-interaction''-n'InputOption::VALUE_NONE'Do not ask any interactive question'),
  926.         ]);
  927.     }
  928.     /**
  929.      * Gets the default commands that should always be available.
  930.      *
  931.      * @return Command[]
  932.      */
  933.     protected function getDefaultCommands()
  934.     {
  935.         return [new HelpCommand(), new ListCommand(), new CompleteCommand(), new DumpCompletionCommand()];
  936.     }
  937.     /**
  938.      * Gets the default helper set with the helpers that should always be available.
  939.      *
  940.      * @return HelperSet
  941.      */
  942.     protected function getDefaultHelperSet()
  943.     {
  944.         return new HelperSet([
  945.             new FormatterHelper(),
  946.             new DebugFormatterHelper(),
  947.             new ProcessHelper(),
  948.             new QuestionHelper(),
  949.         ]);
  950.     }
  951.     /**
  952.      * Returns abbreviated suggestions in string format.
  953.      */
  954.     private function getAbbreviationSuggestions(array $abbrevs): string
  955.     {
  956.         return '    '.implode("\n    "$abbrevs);
  957.     }
  958.     /**
  959.      * Returns the namespace part of the command name.
  960.      *
  961.      * This method is not part of public API and should not be used directly.
  962.      *
  963.      * @return string
  964.      */
  965.     public function extractNamespace(string $nameint $limit null)
  966.     {
  967.         $parts explode(':'$name, -1);
  968.         return implode(':'null === $limit $parts \array_slice($parts0$limit));
  969.     }
  970.     /**
  971.      * Finds alternative of $name among $collection,
  972.      * if nothing is found in $collection, try in $abbrevs.
  973.      *
  974.      * @return string[]
  975.      */
  976.     private function findAlternatives(string $nameiterable $collection): array
  977.     {
  978.         $threshold 1e3;
  979.         $alternatives = [];
  980.         $collectionParts = [];
  981.         foreach ($collection as $item) {
  982.             $collectionParts[$item] = explode(':'$item);
  983.         }
  984.         foreach (explode(':'$name) as $i => $subname) {
  985.             foreach ($collectionParts as $collectionName => $parts) {
  986.                 $exists = isset($alternatives[$collectionName]);
  987.                 if (!isset($parts[$i]) && $exists) {
  988.                     $alternatives[$collectionName] += $threshold;
  989.                     continue;
  990.                 } elseif (!isset($parts[$i])) {
  991.                     continue;
  992.                 }
  993.                 $lev levenshtein($subname$parts[$i]);
  994.                 if ($lev <= \strlen($subname) / || '' !== $subname && str_contains($parts[$i], $subname)) {
  995.                     $alternatives[$collectionName] = $exists $alternatives[$collectionName] + $lev $lev;
  996.                 } elseif ($exists) {
  997.                     $alternatives[$collectionName] += $threshold;
  998.                 }
  999.             }
  1000.         }
  1001.         foreach ($collection as $item) {
  1002.             $lev levenshtein($name$item);
  1003.             if ($lev <= \strlen($name) / || str_contains($item$name)) {
  1004.                 $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev $lev;
  1005.             }
  1006.         }
  1007.         $alternatives array_filter($alternatives, function ($lev) use ($threshold) { return $lev $threshold; });
  1008.         ksort($alternatives\SORT_NATURAL \SORT_FLAG_CASE);
  1009.         return array_keys($alternatives);
  1010.     }
  1011.     /**
  1012.      * Sets the default Command name.
  1013.      *
  1014.      * @return $this
  1015.      */
  1016.     public function setDefaultCommand(string $commandNamebool $isSingleCommand false)
  1017.     {
  1018.         $this->defaultCommand explode('|'ltrim($commandName'|'))[0];
  1019.         if ($isSingleCommand) {
  1020.             // Ensure the command exist
  1021.             $this->find($commandName);
  1022.             $this->singleCommand true;
  1023.         }
  1024.         return $this;
  1025.     }
  1026.     /**
  1027.      * @internal
  1028.      */
  1029.     public function isSingleCommand(): bool
  1030.     {
  1031.         return $this->singleCommand;
  1032.     }
  1033.     private function splitStringByWidth(string $stringint $width): array
  1034.     {
  1035.         // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
  1036.         // additionally, array_slice() is not enough as some character has doubled width.
  1037.         // we need a function to split string not by character count but by string width
  1038.         if (false === $encoding mb_detect_encoding($stringnulltrue)) {
  1039.             return str_split($string$width);
  1040.         }
  1041.         $utf8String mb_convert_encoding($string'utf8'$encoding);
  1042.         $lines = [];
  1043.         $line '';
  1044.         $offset 0;
  1045.         while (preg_match('/.{1,10000}/u'$utf8String$m0$offset)) {
  1046.             $offset += \strlen($m[0]);
  1047.             foreach (preg_split('//u'$m[0]) as $char) {
  1048.                 // test if $char could be appended to current line
  1049.                 if (mb_strwidth($line.$char'utf8') <= $width) {
  1050.                     $line .= $char;
  1051.                     continue;
  1052.                 }
  1053.                 // if not, push current line to array and make new line
  1054.                 $lines[] = str_pad($line$width);
  1055.                 $line $char;
  1056.             }
  1057.         }
  1058.         $lines[] = \count($lines) ? str_pad($line$width) : $line;
  1059.         mb_convert_variables($encoding'utf8'$lines);
  1060.         return $lines;
  1061.     }
  1062.     /**
  1063.      * Returns all namespaces of the command name.
  1064.      *
  1065.      * @return string[]
  1066.      */
  1067.     private function extractAllNamespaces(string $name): array
  1068.     {
  1069.         // -1 as third argument is needed to skip the command short name when exploding
  1070.         $parts explode(':'$name, -1);
  1071.         $namespaces = [];
  1072.         foreach ($parts as $part) {
  1073.             if (\count($namespaces)) {
  1074.                 $namespaces[] = end($namespaces).':'.$part;
  1075.             } else {
  1076.                 $namespaces[] = $part;
  1077.             }
  1078.         }
  1079.         return $namespaces;
  1080.     }
  1081.     private function init()
  1082.     {
  1083.         if ($this->initialized) {
  1084.             return;
  1085.         }
  1086.         $this->initialized true;
  1087.         foreach ($this->getDefaultCommands() as $command) {
  1088.             $this->add($command);
  1089.         }
  1090.     }
  1091. }