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