vendor/symfony/console/Application.php line 220

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