4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console;
14 use Symfony\Component\Console\Command\Command;
15 use Symfony\Component\Console\Command\HelpCommand;
16 use Symfony\Component\Console\Command\ListCommand;
17 use Symfony\Component\Console\CommandLoader\CommandLoaderInterface;
18 use Symfony\Component\Console\Event\ConsoleCommandEvent;
19 use Symfony\Component\Console\Event\ConsoleErrorEvent;
20 use Symfony\Component\Console\Event\ConsoleExceptionEvent;
21 use Symfony\Component\Console\Event\ConsoleTerminateEvent;
22 use Symfony\Component\Console\Exception\CommandNotFoundException;
23 use Symfony\Component\Console\Exception\ExceptionInterface;
24 use Symfony\Component\Console\Exception\LogicException;
25 use Symfony\Component\Console\Formatter\OutputFormatter;
26 use Symfony\Component\Console\Helper\DebugFormatterHelper;
27 use Symfony\Component\Console\Helper\FormatterHelper;
28 use Symfony\Component\Console\Helper\Helper;
29 use Symfony\Component\Console\Helper\HelperSet;
30 use Symfony\Component\Console\Helper\ProcessHelper;
31 use Symfony\Component\Console\Helper\QuestionHelper;
32 use Symfony\Component\Console\Input\ArgvInput;
33 use Symfony\Component\Console\Input\ArrayInput;
34 use Symfony\Component\Console\Input\InputArgument;
35 use Symfony\Component\Console\Input\InputAwareInterface;
36 use Symfony\Component\Console\Input\InputDefinition;
37 use Symfony\Component\Console\Input\InputInterface;
38 use Symfony\Component\Console\Input\InputOption;
39 use Symfony\Component\Console\Input\StreamableInputInterface;
40 use Symfony\Component\Console\Output\ConsoleOutput;
41 use Symfony\Component\Console\Output\ConsoleOutputInterface;
42 use Symfony\Component\Console\Output\OutputInterface;
43 use Symfony\Component\Debug\ErrorHandler;
44 use Symfony\Component\Debug\Exception\FatalThrowableError;
45 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
48 * An Application is the container for a collection of commands.
50 * It is the main entry point of a Console application.
52 * This class is optimized for a standard CLI environment.
56 * $app = new Application('myapp', '1.0 (stable)');
57 * $app->add(new SimpleCommand());
60 * @author Fabien Potencier <fabien@symfony.com>
64 private $commands = array();
65 private $wantHelps = false;
66 private $runningCommand;
69 private $commandLoader;
70 private $catchExceptions = true;
71 private $autoExit = true;
76 private $defaultCommand;
77 private $singleCommand;
81 * @param string $name The name of the application
82 * @param string $version The version of the application
84 public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
87 $this->version = $version;
88 $this->terminal = new Terminal();
89 $this->defaultCommand = 'list';
92 public function setDispatcher(EventDispatcherInterface $dispatcher)
94 $this->dispatcher = $dispatcher;
97 public function setCommandLoader(CommandLoaderInterface $commandLoader)
99 $this->commandLoader = $commandLoader;
103 * Runs the current application.
105 * @return int 0 if everything went fine, or an error code
107 * @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}.
109 public function run(InputInterface $input = null, OutputInterface $output = null)
111 putenv('LINES='.$this->terminal->getHeight());
112 putenv('COLUMNS='.$this->terminal->getWidth());
114 if (null === $input) {
115 $input = new ArgvInput();
118 if (null === $output) {
119 $output = new ConsoleOutput();
122 $renderException = function ($e) use ($output) {
123 if (!$e instanceof \Exception) {
124 $e = class_exists(FatalThrowableError::class) ? new FatalThrowableError($e) : new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
126 if ($output instanceof ConsoleOutputInterface) {
127 $this->renderException($e, $output->getErrorOutput());
129 $this->renderException($e, $output);
132 if ($phpHandler = set_exception_handler($renderException)) {
133 restore_exception_handler();
134 if (!\is_array($phpHandler) || !$phpHandler[0] instanceof ErrorHandler) {
135 $debugHandler = true;
136 } elseif ($debugHandler = $phpHandler[0]->setExceptionHandler($renderException)) {
137 $phpHandler[0]->setExceptionHandler($debugHandler);
141 if (null !== $this->dispatcher && $this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) {
142 @trigger_error(sprintf('The "ConsoleEvents::EXCEPTION" event is deprecated since Symfony 3.3 and will be removed in 4.0. Listen to the "ConsoleEvents::ERROR" event instead.'), E_USER_DEPRECATED);
145 $this->configureIO($input, $output);
148 $exitCode = $this->doRun($input, $output);
149 } catch (\Exception $e) {
150 if (!$this->catchExceptions) {
154 $renderException($e);
156 $exitCode = $e->getCode();
157 if (is_numeric($exitCode)) {
158 $exitCode = (int) $exitCode;
159 if (0 === $exitCode) {
166 // if the exception handler changed, keep it
167 // otherwise, unregister $renderException
169 if (set_exception_handler($renderException) === $renderException) {
170 restore_exception_handler();
172 restore_exception_handler();
173 } elseif (!$debugHandler) {
174 $finalHandler = $phpHandler[0]->setExceptionHandler(null);
175 if ($finalHandler !== $renderException) {
176 $phpHandler[0]->setExceptionHandler($finalHandler);
181 if ($this->autoExit) {
182 if ($exitCode > 255) {
193 * Runs the current application.
195 * @return int 0 if everything went fine, or an error code
197 public function doRun(InputInterface $input, OutputInterface $output)
199 if (true === $input->hasParameterOption(array('--version', '-V'), true)) {
200 $output->writeln($this->getLongVersion());
205 $name = $this->getCommandName($input);
206 if (true === $input->hasParameterOption(array('--help', '-h'), true)) {
209 $input = new ArrayInput(array('command_name' => $this->defaultCommand));
211 $this->wantHelps = true;
216 $name = $this->defaultCommand;
217 $definition = $this->getDefinition();
218 $definition->setArguments(array_merge(
219 $definition->getArguments(),
221 'command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name),
227 $e = $this->runningCommand = null;
228 // the command name MUST be the first element of the input
229 $command = $this->find($name);
230 } catch (\Exception $e) {
231 } catch (\Throwable $e) {
234 if (null !== $this->dispatcher) {
235 $event = new ConsoleErrorEvent($input, $output, $e);
236 $this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
237 $e = $event->getError();
239 if (0 === $event->getExitCode()) {
247 $this->runningCommand = $command;
248 $exitCode = $this->doRunCommand($command, $input, $output);
249 $this->runningCommand = null;
254 public function setHelperSet(HelperSet $helperSet)
256 $this->helperSet = $helperSet;
260 * Get the helper set associated with the command.
262 * @return HelperSet The HelperSet instance associated with this command
264 public function getHelperSet()
266 if (!$this->helperSet) {
267 $this->helperSet = $this->getDefaultHelperSet();
270 return $this->helperSet;
273 public function setDefinition(InputDefinition $definition)
275 $this->definition = $definition;
279 * Gets the InputDefinition related to this Application.
281 * @return InputDefinition The InputDefinition instance
283 public function getDefinition()
285 if (!$this->definition) {
286 $this->definition = $this->getDefaultInputDefinition();
289 if ($this->singleCommand) {
290 $inputDefinition = $this->definition;
291 $inputDefinition->setArguments();
293 return $inputDefinition;
296 return $this->definition;
300 * Gets the help message.
302 * @return string A help message
304 public function getHelp()
306 return $this->getLongVersion();
310 * Gets whether to catch exceptions or not during commands execution.
312 * @return bool Whether to catch exceptions or not during commands execution
314 public function areExceptionsCaught()
316 return $this->catchExceptions;
320 * Sets whether to catch exceptions or not during commands execution.
322 * @param bool $boolean Whether to catch exceptions or not during commands execution
324 public function setCatchExceptions($boolean)
326 $this->catchExceptions = (bool) $boolean;
330 * Gets whether to automatically exit after a command execution or not.
332 * @return bool Whether to automatically exit after a command execution or not
334 public function isAutoExitEnabled()
336 return $this->autoExit;
340 * Sets whether to automatically exit after a command execution or not.
342 * @param bool $boolean Whether to automatically exit after a command execution or not
344 public function setAutoExit($boolean)
346 $this->autoExit = (bool) $boolean;
350 * Gets the name of the application.
352 * @return string The application name
354 public function getName()
360 * Sets the application name.
362 * @param string $name The application name
364 public function setName($name)
370 * Gets the application version.
372 * @return string The application version
374 public function getVersion()
376 return $this->version;
380 * Sets the application version.
382 * @param string $version The application version
384 public function setVersion($version)
386 $this->version = $version;
390 * Returns the long version of the application.
392 * @return string The long application version
394 public function getLongVersion()
396 if ('UNKNOWN' !== $this->getName()) {
397 if ('UNKNOWN' !== $this->getVersion()) {
398 return sprintf('%s <info>%s</info>', $this->getName(), $this->getVersion());
401 return $this->getName();
404 return 'Console Tool';
408 * Registers a new command.
410 * @param string $name The command name
412 * @return Command The newly created command
414 public function register($name)
416 return $this->add(new Command($name));
420 * Adds an array of command objects.
422 * If a Command is not enabled it will not be added.
424 * @param Command[] $commands An array of commands
426 public function addCommands(array $commands)
428 foreach ($commands as $command) {
429 $this->add($command);
434 * Adds a command object.
436 * If a command with the same name already exists, it will be overridden.
437 * If the command is not enabled it will not be added.
439 * @return Command|null The registered command if enabled or null
441 public function add(Command $command)
445 $command->setApplication($this);
447 if (!$command->isEnabled()) {
448 $command->setApplication(null);
453 if (null === $command->getDefinition()) {
454 throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', \get_class($command)));
457 if (!$command->getName()) {
458 throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', \get_class($command)));
461 $this->commands[$command->getName()] = $command;
463 foreach ($command->getAliases() as $alias) {
464 $this->commands[$alias] = $command;
471 * Returns a registered command by name or alias.
473 * @param string $name The command name or alias
475 * @return Command A Command object
477 * @throws CommandNotFoundException When given command name does not exist
479 public function get($name)
483 if (!$this->has($name)) {
484 throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name));
487 $command = $this->commands[$name];
489 if ($this->wantHelps) {
490 $this->wantHelps = false;
492 $helpCommand = $this->get('help');
493 $helpCommand->setCommand($command);
502 * Returns true if the command exists, false otherwise.
504 * @param string $name The command name or alias
506 * @return bool true if the command exists, false otherwise
508 public function has($name)
512 return isset($this->commands[$name]) || ($this->commandLoader && $this->commandLoader->has($name) && $this->add($this->commandLoader->get($name)));
516 * Returns an array of all unique namespaces used by currently registered commands.
518 * It does not return the global namespace which always exists.
520 * @return string[] An array of namespaces
522 public function getNamespaces()
524 $namespaces = array();
525 foreach ($this->all() as $command) {
526 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
528 foreach ($command->getAliases() as $alias) {
529 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias));
533 return array_values(array_unique(array_filter($namespaces)));
537 * Finds a registered namespace by a name or an abbreviation.
539 * @param string $namespace A namespace or abbreviation to search for
541 * @return string A registered namespace
543 * @throws CommandNotFoundException When namespace is incorrect or ambiguous
545 public function findNamespace($namespace)
547 $allNamespaces = $this->getNamespaces();
548 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $namespace);
549 $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
551 if (empty($namespaces)) {
552 $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
554 if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
555 if (1 == \count($alternatives)) {
556 $message .= "\n\nDid you mean this?\n ";
558 $message .= "\n\nDid you mean one of these?\n ";
561 $message .= implode("\n ", $alternatives);
564 throw new CommandNotFoundException($message, $alternatives);
567 $exact = \in_array($namespace, $namespaces, true);
568 if (\count($namespaces) > 1 && !$exact) {
569 throw new CommandNotFoundException(sprintf("The namespace \"%s\" is ambiguous.\nDid you mean one of these?\n%s", $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
572 return $exact ? $namespace : reset($namespaces);
576 * Finds a command by name or alias.
578 * Contrary to get, this command tries to find the best
579 * match if you give it an abbreviation of a name or alias.
581 * @param string $name A command name or a command alias
583 * @return Command A Command instance
585 * @throws CommandNotFoundException When command name is incorrect or ambiguous
587 public function find($name)
592 $allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
593 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
594 $commands = preg_grep('{^'.$expr.'}', $allCommands);
596 if (empty($commands)) {
597 $commands = preg_grep('{^'.$expr.'}i', $allCommands);
600 // if no commands matched or we just matched namespaces
601 if (empty($commands) || \count(preg_grep('{^'.$expr.'$}i', $commands)) < 1) {
602 if (false !== $pos = strrpos($name, ':')) {
603 // check if a namespace exists and contains commands
604 $this->findNamespace(substr($name, 0, $pos));
607 $message = sprintf('Command "%s" is not defined.', $name);
609 if ($alternatives = $this->findAlternatives($name, $allCommands)) {
610 if (1 == \count($alternatives)) {
611 $message .= "\n\nDid you mean this?\n ";
613 $message .= "\n\nDid you mean one of these?\n ";
615 $message .= implode("\n ", $alternatives);
618 throw new CommandNotFoundException($message, $alternatives);
621 // filter out aliases for commands which are already on the list
622 if (\count($commands) > 1) {
623 $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands;
624 $commands = array_unique(array_filter($commands, function ($nameOrAlias) use ($commandList, $commands, &$aliases) {
625 $commandName = $commandList[$nameOrAlias] instanceof Command ? $commandList[$nameOrAlias]->getName() : $nameOrAlias;
626 $aliases[$nameOrAlias] = $commandName;
628 return $commandName === $nameOrAlias || !\in_array($commandName, $commands);
632 $exact = \in_array($name, $commands, true) || isset($aliases[$name]);
633 if (\count($commands) > 1 && !$exact) {
634 $usableWidth = $this->terminal->getWidth() - 10;
635 $abbrevs = array_values($commands);
637 foreach ($abbrevs as $abbrev) {
638 $maxLen = max(Helper::strlen($abbrev), $maxLen);
640 $abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen) {
641 if (!$commandList[$cmd] instanceof Command) {
644 $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription();
646 return Helper::strlen($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev;
647 }, array_values($commands));
648 $suggestions = $this->getAbbreviationSuggestions($abbrevs);
650 throw new CommandNotFoundException(sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s", $name, $suggestions), array_values($commands));
653 return $this->get($exact ? $name : reset($commands));
657 * Gets the commands (registered in the given namespace if provided).
659 * The array keys are the full names and the values the command instances.
661 * @param string $namespace A namespace name
663 * @return Command[] An array of Command instances
665 public function all($namespace = null)
669 if (null === $namespace) {
670 if (!$this->commandLoader) {
671 return $this->commands;
674 $commands = $this->commands;
675 foreach ($this->commandLoader->getNames() as $name) {
676 if (!isset($commands[$name]) && $this->has($name)) {
677 $commands[$name] = $this->get($name);
685 foreach ($this->commands as $name => $command) {
686 if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
687 $commands[$name] = $command;
691 if ($this->commandLoader) {
692 foreach ($this->commandLoader->getNames() as $name) {
693 if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) {
694 $commands[$name] = $this->get($name);
703 * Returns an array of possible abbreviations given a set of names.
705 * @param array $names An array of names
707 * @return array An array of abbreviations
709 public static function getAbbreviations($names)
712 foreach ($names as $name) {
713 for ($len = \strlen($name); $len > 0; --$len) {
714 $abbrev = substr($name, 0, $len);
715 $abbrevs[$abbrev][] = $name;
723 * Renders a caught exception.
725 public function renderException(\Exception $e, OutputInterface $output)
727 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
729 $this->doRenderException($e, $output);
731 if (null !== $this->runningCommand) {
732 $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
733 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
737 protected function doRenderException(\Exception $e, OutputInterface $output)
740 $message = trim($e->getMessage());
741 if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
742 $title = sprintf(' [%s%s] ', \get_class($e), 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
743 $len = Helper::strlen($title);
748 $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX;
749 // HHVM only accepts 32 bits integer in str_split, even when PHP_INT_MAX is a 64 bit integer: https://github.com/facebook/hhvm/issues/1327
750 if (\defined('HHVM_VERSION') && $width > 1 << 31) {
754 foreach ('' !== $message ? preg_split('/\r?\n/', $message) : array() as $line) {
755 foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
756 // pre-format lines to get the right string length
757 $lineLength = Helper::strlen($line) + 4;
758 $lines[] = array($line, $lineLength);
760 $len = max($lineLength, $len);
765 if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
766 $messages[] = sprintf('<comment>%s</comment>', OutputFormatter::escape(sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a')));
768 $messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
769 if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
770 $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
772 foreach ($lines as $line) {
773 $messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
775 $messages[] = $emptyLine;
778 $output->writeln($messages, OutputInterface::VERBOSITY_QUIET);
780 if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
781 $output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
783 // exception related properties
784 $trace = $e->getTrace();
786 for ($i = 0, $count = \count($trace); $i < $count; ++$i) {
787 $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
788 $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
789 $function = $trace[$i]['function'];
790 $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
791 $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
793 $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET);
796 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
798 } while ($e = $e->getPrevious());
802 * Tries to figure out the terminal width in which this application runs.
806 * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead.
808 protected function getTerminalWidth()
810 @trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), E_USER_DEPRECATED);
812 return $this->terminal->getWidth();
816 * Tries to figure out the terminal height in which this application runs.
820 * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead.
822 protected function getTerminalHeight()
824 @trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), E_USER_DEPRECATED);
826 return $this->terminal->getHeight();
830 * Tries to figure out the terminal dimensions based on the current environment.
832 * @return array Array containing width and height
834 * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead.
836 public function getTerminalDimensions()
838 @trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), E_USER_DEPRECATED);
840 return array($this->terminal->getWidth(), $this->terminal->getHeight());
844 * Sets terminal dimensions.
846 * Can be useful to force terminal dimensions for functional tests.
848 * @param int $width The width
849 * @param int $height The height
853 * @deprecated since version 3.2, to be removed in 4.0. Set the COLUMNS and LINES env vars instead.
855 public function setTerminalDimensions($width, $height)
857 @trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Set the COLUMNS and LINES env vars instead.', __METHOD__), E_USER_DEPRECATED);
859 putenv('COLUMNS='.$width);
860 putenv('LINES='.$height);
866 * Configures the input and output instances based on the user arguments and options.
868 protected function configureIO(InputInterface $input, OutputInterface $output)
870 if (true === $input->hasParameterOption(array('--ansi'), true)) {
871 $output->setDecorated(true);
872 } elseif (true === $input->hasParameterOption(array('--no-ansi'), true)) {
873 $output->setDecorated(false);
876 if (true === $input->hasParameterOption(array('--no-interaction', '-n'), true)) {
877 $input->setInteractive(false);
878 } elseif (\function_exists('posix_isatty')) {
881 if ($input instanceof StreamableInputInterface) {
882 $inputStream = $input->getStream();
885 // This check ensures that calling QuestionHelper::setInputStream() works
886 // To be removed in 4.0 (in the same time as QuestionHelper::setInputStream)
887 if (!$inputStream && $this->getHelperSet()->has('question')) {
888 $inputStream = $this->getHelperSet()->get('question')->getInputStream(false);
891 if (!@posix_isatty($inputStream) && false === getenv('SHELL_INTERACTIVE')) {
892 $input->setInteractive(false);
896 switch ($shellVerbosity = (int) getenv('SHELL_VERBOSITY')) {
897 case -1: $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); break;
898 case 1: $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); break;
899 case 2: $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); break;
900 case 3: $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); break;
901 default: $shellVerbosity = 0; break;
904 if (true === $input->hasParameterOption(array('--quiet', '-q'), true)) {
905 $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
906 $shellVerbosity = -1;
908 if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true)) {
909 $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
911 } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true)) {
912 $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
914 } elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) {
915 $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
920 if (-1 === $shellVerbosity) {
921 $input->setInteractive(false);
924 putenv('SHELL_VERBOSITY='.$shellVerbosity);
925 $_ENV['SHELL_VERBOSITY'] = $shellVerbosity;
926 $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity;
930 * Runs the current command.
932 * If an event dispatcher has been attached to the application,
933 * events are also dispatched during the life-cycle of the command.
935 * @return int 0 if everything went fine, or an error code
937 protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
939 foreach ($command->getHelperSet() as $helper) {
940 if ($helper instanceof InputAwareInterface) {
941 $helper->setInput($input);
945 if (null === $this->dispatcher) {
946 return $command->run($input, $output);
949 // bind before the console.command event, so the listeners have access to input options/arguments
951 $command->mergeApplicationDefinition();
952 $input->bind($command->getDefinition());
953 } catch (ExceptionInterface $e) {
954 // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
957 $event = new ConsoleCommandEvent($command, $input, $output);
961 $this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
963 if ($event->commandShouldRun()) {
964 $exitCode = $command->run($input, $output);
966 $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
968 } catch (\Exception $e) {
969 } catch (\Throwable $e) {
972 if ($this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) {
973 $x = $e instanceof \Exception ? $e : new FatalThrowableError($e);
974 $event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode());
975 $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
977 if ($x !== $event->getException()) {
978 $e = $event->getException();
981 $event = new ConsoleErrorEvent($input, $output, $e, $command);
982 $this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
983 $e = $event->getError();
985 if (0 === $exitCode = $event->getExitCode()) {
990 $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
991 $this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
997 return $event->getExitCode();
1001 * Gets the name of the command based on input.
1003 * @return string The command name
1005 protected function getCommandName(InputInterface $input)
1007 return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument();
1011 * Gets the default input definition.
1013 * @return InputDefinition An InputDefinition instance
1015 protected function getDefaultInputDefinition()
1017 return new InputDefinition(array(
1018 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
1020 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
1021 new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
1022 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'),
1023 new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
1024 new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
1025 new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
1026 new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
1031 * Gets the default commands that should always be available.
1033 * @return Command[] An array of default Command instances
1035 protected function getDefaultCommands()
1037 return array(new HelpCommand(), new ListCommand());
1041 * Gets the default helper set with the helpers that should always be available.
1043 * @return HelperSet A HelperSet instance
1045 protected function getDefaultHelperSet()
1047 return new HelperSet(array(
1048 new FormatterHelper(),
1049 new DebugFormatterHelper(),
1050 new ProcessHelper(),
1051 new QuestionHelper(),
1056 * Returns abbreviated suggestions in string format.
1058 * @param array $abbrevs Abbreviated suggestions to convert
1060 * @return string A formatted string of abbreviated suggestions
1062 private function getAbbreviationSuggestions($abbrevs)
1064 return ' '.implode("\n ", $abbrevs);
1068 * Returns the namespace part of the command name.
1070 * This method is not part of public API and should not be used directly.
1072 * @param string $name The full name of the command
1073 * @param string $limit The maximum number of parts of the namespace
1075 * @return string The namespace of the command
1077 public function extractNamespace($name, $limit = null)
1079 $parts = explode(':', $name);
1082 return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit));
1086 * Finds alternative of $name among $collection,
1087 * if nothing is found in $collection, try in $abbrevs.
1089 * @param string $name The string
1090 * @param iterable $collection The collection
1092 * @return string[] A sorted array of similar string
1094 private function findAlternatives($name, $collection)
1097 $alternatives = array();
1099 $collectionParts = array();
1100 foreach ($collection as $item) {
1101 $collectionParts[$item] = explode(':', $item);
1104 foreach (explode(':', $name) as $i => $subname) {
1105 foreach ($collectionParts as $collectionName => $parts) {
1106 $exists = isset($alternatives[$collectionName]);
1107 if (!isset($parts[$i]) && $exists) {
1108 $alternatives[$collectionName] += $threshold;
1110 } elseif (!isset($parts[$i])) {
1114 $lev = levenshtein($subname, $parts[$i]);
1115 if ($lev <= \strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
1116 $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
1117 } elseif ($exists) {
1118 $alternatives[$collectionName] += $threshold;
1123 foreach ($collection as $item) {
1124 $lev = levenshtein($name, $item);
1125 if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
1126 $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
1130 $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
1131 ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE);
1133 return array_keys($alternatives);
1137 * Sets the default Command name.
1139 * @param string $commandName The Command name
1140 * @param bool $isSingleCommand Set to true if there is only one command in this application
1144 public function setDefaultCommand($commandName, $isSingleCommand = false)
1146 $this->defaultCommand = $commandName;
1148 if ($isSingleCommand) {
1149 // Ensure the command exist
1150 $this->find($commandName);
1152 $this->singleCommand = true;
1158 private function splitStringByWidth($string, $width)
1160 // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
1161 // additionally, array_slice() is not enough as some character has doubled width.
1162 // we need a function to split string not by character count but by string width
1163 if (false === $encoding = mb_detect_encoding($string, null, true)) {
1164 return str_split($string, $width);
1167 $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
1170 foreach (preg_split('//u', $utf8String) as $char) {
1171 // test if $char could be appended to current line
1172 if (mb_strwidth($line.$char, 'utf8') <= $width) {
1176 // if not, push current line to array and make new line
1177 $lines[] = str_pad($line, $width);
1181 $lines[] = \count($lines) ? str_pad($line, $width) : $line;
1183 mb_convert_variables($encoding, 'utf8', $lines);
1189 * Returns all namespaces of the command name.
1191 * @param string $name The full name of the command
1193 * @return string[] The namespaces of the command
1195 private function extractAllNamespaces($name)
1197 // -1 as third argument is needed to skip the command short name when exploding
1198 $parts = explode(':', $name, -1);
1199 $namespaces = array();
1201 foreach ($parts as $part) {
1202 if (\count($namespaces)) {
1203 $namespaces[] = end($namespaces).':'.$part;
1205 $namespaces[] = $part;
1212 private function init()
1214 if ($this->initialized) {
1217 $this->initialized = true;
1219 foreach ($this->getDefaultCommands() as $command) {
1220 $this->add($command);