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