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\Descriptor\TextDescriptor;
15 use Symfony\Component\Console\Descriptor\XmlDescriptor;
16 use Symfony\Component\Console\Exception\ExceptionInterface;
17 use Symfony\Component\Console\Formatter\OutputFormatter;
18 use Symfony\Component\Console\Helper\DebugFormatterHelper;
19 use Symfony\Component\Console\Helper\Helper;
20 use Symfony\Component\Console\Helper\ProcessHelper;
21 use Symfony\Component\Console\Helper\QuestionHelper;
22 use Symfony\Component\Console\Input\InputInterface;
23 use Symfony\Component\Console\Input\ArgvInput;
24 use Symfony\Component\Console\Input\ArrayInput;
25 use Symfony\Component\Console\Input\InputDefinition;
26 use Symfony\Component\Console\Input\InputOption;
27 use Symfony\Component\Console\Input\InputArgument;
28 use Symfony\Component\Console\Input\InputAwareInterface;
29 use Symfony\Component\Console\Output\BufferedOutput;
30 use Symfony\Component\Console\Output\OutputInterface;
31 use Symfony\Component\Console\Output\ConsoleOutput;
32 use Symfony\Component\Console\Output\ConsoleOutputInterface;
33 use Symfony\Component\Console\Command\Command;
34 use Symfony\Component\Console\Command\HelpCommand;
35 use Symfony\Component\Console\Command\ListCommand;
36 use Symfony\Component\Console\Helper\HelperSet;
37 use Symfony\Component\Console\Helper\FormatterHelper;
38 use Symfony\Component\Console\Helper\DialogHelper;
39 use Symfony\Component\Console\Helper\ProgressHelper;
40 use Symfony\Component\Console\Helper\TableHelper;
41 use Symfony\Component\Console\Event\ConsoleCommandEvent;
42 use Symfony\Component\Console\Event\ConsoleExceptionEvent;
43 use Symfony\Component\Console\Event\ConsoleTerminateEvent;
44 use Symfony\Component\Console\Exception\CommandNotFoundException;
45 use Symfony\Component\Console\Exception\LogicException;
46 use Symfony\Component\Debug\Exception\FatalThrowableError;
47 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
50 * An Application is the container for a collection of commands.
52 * It is the main entry point of a Console application.
54 * This class is optimized for a standard CLI environment.
58 * $app = new Application('myapp', '1.0 (stable)');
59 * $app->add(new SimpleCommand());
62 * @author Fabien Potencier <fabien@symfony.com>
66 private $commands = array();
67 private $wantHelps = false;
68 private $runningCommand;
71 private $catchExceptions = true;
72 private $autoExit = true;
76 private $terminalDimensions;
77 private $defaultCommand;
82 * @param string $name The name of the application
83 * @param string $version The version of the application
85 public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
88 $this->version = $version;
89 $this->defaultCommand = 'list';
90 $this->helperSet = $this->getDefaultHelperSet();
91 $this->definition = $this->getDefaultInputDefinition();
93 foreach ($this->getDefaultCommands() as $command) {
98 public function setDispatcher(EventDispatcherInterface $dispatcher)
100 $this->dispatcher = $dispatcher;
104 * Runs the current application.
106 * @param InputInterface $input An Input instance
107 * @param OutputInterface $output An Output instance
109 * @return int 0 if everything went fine, or an error code
111 * @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}.
113 public function run(InputInterface $input = null, OutputInterface $output = null)
115 if (null === $input) {
116 $input = new ArgvInput();
119 if (null === $output) {
120 $output = new ConsoleOutput();
123 $this->configureIO($input, $output);
127 $exitCode = $this->doRun($input, $output);
128 } catch (\Exception $x) {
130 } catch (\Throwable $x) {
131 $e = new FatalThrowableError($x);
135 if (!$this->catchExceptions || !$x instanceof \Exception) {
139 if ($output instanceof ConsoleOutputInterface) {
140 $this->renderException($e, $output->getErrorOutput());
142 $this->renderException($e, $output);
145 $exitCode = $e->getCode();
146 if (is_numeric($exitCode)) {
147 $exitCode = (int) $exitCode;
148 if (0 === $exitCode) {
156 if ($this->autoExit) {
157 if ($exitCode > 255) {
168 * Runs the current application.
170 * @param InputInterface $input An Input instance
171 * @param OutputInterface $output An Output instance
173 * @return int 0 if everything went fine, or an error code
175 public function doRun(InputInterface $input, OutputInterface $output)
177 if (true === $input->hasParameterOption(array('--version', '-V'))) {
178 $output->writeln($this->getLongVersion());
183 $name = $this->getCommandName($input);
184 if (true === $input->hasParameterOption(array('--help', '-h'))) {
187 $input = new ArrayInput(array('command' => 'help'));
189 $this->wantHelps = true;
194 $name = $this->defaultCommand;
195 $input = new ArrayInput(array('command' => $this->defaultCommand));
198 $this->runningCommand = null;
199 // the command name MUST be the first element of the input
200 $command = $this->find($name);
202 $this->runningCommand = $command;
203 $exitCode = $this->doRunCommand($command, $input, $output);
204 $this->runningCommand = null;
210 * Set a helper set to be used with the command.
212 * @param HelperSet $helperSet The helper set
214 public function setHelperSet(HelperSet $helperSet)
216 $this->helperSet = $helperSet;
220 * Get the helper set associated with the command.
222 * @return HelperSet The HelperSet instance associated with this command
224 public function getHelperSet()
226 return $this->helperSet;
230 * Set an input definition to be used with this application.
232 * @param InputDefinition $definition The input definition
234 public function setDefinition(InputDefinition $definition)
236 $this->definition = $definition;
240 * Gets the InputDefinition related to this Application.
242 * @return InputDefinition The InputDefinition instance
244 public function getDefinition()
246 return $this->definition;
250 * Gets the help message.
252 * @return string A help message
254 public function getHelp()
256 return $this->getLongVersion();
260 * Sets whether to catch exceptions or not during commands execution.
262 * @param bool $boolean Whether to catch exceptions or not during commands execution
264 public function setCatchExceptions($boolean)
266 $this->catchExceptions = (bool) $boolean;
270 * Sets whether to automatically exit after a command execution or not.
272 * @param bool $boolean Whether to automatically exit after a command execution or not
274 public function setAutoExit($boolean)
276 $this->autoExit = (bool) $boolean;
280 * Gets the name of the application.
282 * @return string The application name
284 public function getName()
290 * Sets the application name.
292 * @param string $name The application name
294 public function setName($name)
300 * Gets the application version.
302 * @return string The application version
304 public function getVersion()
306 return $this->version;
310 * Sets the application version.
312 * @param string $version The application version
314 public function setVersion($version)
316 $this->version = $version;
320 * Returns the long version of the application.
322 * @return string The long application version
324 public function getLongVersion()
326 if ('UNKNOWN' !== $this->getName()) {
327 if ('UNKNOWN' !== $this->getVersion()) {
328 return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
331 return sprintf('<info>%s</info>', $this->getName());
334 return '<info>Console Tool</info>';
338 * Registers a new command.
340 * @param string $name The command name
342 * @return Command The newly created command
344 public function register($name)
346 return $this->add(new Command($name));
350 * Adds an array of command objects.
352 * If a Command is not enabled it will not be added.
354 * @param Command[] $commands An array of commands
356 public function addCommands(array $commands)
358 foreach ($commands as $command) {
359 $this->add($command);
364 * Adds a command object.
366 * If a command with the same name already exists, it will be overridden.
367 * If the command is not enabled it will not be added.
369 * @param Command $command A Command object
371 * @return Command|null The registered command if enabled or null
373 public function add(Command $command)
375 $command->setApplication($this);
377 if (!$command->isEnabled()) {
378 $command->setApplication(null);
383 if (null === $command->getDefinition()) {
384 throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', get_class($command)));
387 $this->commands[$command->getName()] = $command;
389 foreach ($command->getAliases() as $alias) {
390 $this->commands[$alias] = $command;
397 * Returns a registered command by name or alias.
399 * @param string $name The command name or alias
401 * @return Command A Command object
403 * @throws CommandNotFoundException When given command name does not exist
405 public function get($name)
407 if (!isset($this->commands[$name])) {
408 throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name));
411 $command = $this->commands[$name];
413 if ($this->wantHelps) {
414 $this->wantHelps = false;
416 $helpCommand = $this->get('help');
417 $helpCommand->setCommand($command);
426 * Returns true if the command exists, false otherwise.
428 * @param string $name The command name or alias
430 * @return bool true if the command exists, false otherwise
432 public function has($name)
434 return isset($this->commands[$name]);
438 * Returns an array of all unique namespaces used by currently registered commands.
440 * It does not return the global namespace which always exists.
442 * @return string[] An array of namespaces
444 public function getNamespaces()
446 $namespaces = array();
447 foreach ($this->all() as $command) {
448 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
450 foreach ($command->getAliases() as $alias) {
451 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias));
455 return array_values(array_unique(array_filter($namespaces)));
459 * Finds a registered namespace by a name or an abbreviation.
461 * @param string $namespace A namespace or abbreviation to search for
463 * @return string A registered namespace
465 * @throws CommandNotFoundException When namespace is incorrect or ambiguous
467 public function findNamespace($namespace)
469 $allNamespaces = $this->getNamespaces();
470 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $namespace);
471 $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
473 if (empty($namespaces)) {
474 $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
476 if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
477 if (1 == count($alternatives)) {
478 $message .= "\n\nDid you mean this?\n ";
480 $message .= "\n\nDid you mean one of these?\n ";
483 $message .= implode("\n ", $alternatives);
486 throw new CommandNotFoundException($message, $alternatives);
489 $exact = in_array($namespace, $namespaces, true);
490 if (count($namespaces) > 1 && !$exact) {
491 throw new CommandNotFoundException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
494 return $exact ? $namespace : reset($namespaces);
498 * Finds a command by name or alias.
500 * Contrary to get, this command tries to find the best
501 * match if you give it an abbreviation of a name or alias.
503 * @param string $name A command name or a command alias
505 * @return Command A Command instance
507 * @throws CommandNotFoundException When command name is incorrect or ambiguous
509 public function find($name)
511 $allCommands = array_keys($this->commands);
512 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
513 $commands = preg_grep('{^'.$expr.'}', $allCommands);
515 if (empty($commands) || count(preg_grep('{^'.$expr.'$}', $commands)) < 1) {
516 if (false !== $pos = strrpos($name, ':')) {
517 // check if a namespace exists and contains commands
518 $this->findNamespace(substr($name, 0, $pos));
521 $message = sprintf('Command "%s" is not defined.', $name);
523 if ($alternatives = $this->findAlternatives($name, $allCommands)) {
524 if (1 == count($alternatives)) {
525 $message .= "\n\nDid you mean this?\n ";
527 $message .= "\n\nDid you mean one of these?\n ";
529 $message .= implode("\n ", $alternatives);
532 throw new CommandNotFoundException($message, $alternatives);
535 // filter out aliases for commands which are already on the list
536 if (count($commands) > 1) {
537 $commandList = $this->commands;
538 $commands = array_filter($commands, function ($nameOrAlias) use ($commandList, $commands) {
539 $commandName = $commandList[$nameOrAlias]->getName();
541 return $commandName === $nameOrAlias || !in_array($commandName, $commands);
545 $exact = in_array($name, $commands, true);
546 if (count($commands) > 1 && !$exact) {
547 $suggestions = $this->getAbbreviationSuggestions(array_values($commands));
549 throw new CommandNotFoundException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions), array_values($commands));
552 return $this->get($exact ? $name : reset($commands));
556 * Gets the commands (registered in the given namespace if provided).
558 * The array keys are the full names and the values the command instances.
560 * @param string $namespace A namespace name
562 * @return Command[] An array of Command instances
564 public function all($namespace = null)
566 if (null === $namespace) {
567 return $this->commands;
571 foreach ($this->commands as $name => $command) {
572 if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
573 $commands[$name] = $command;
581 * Returns an array of possible abbreviations given a set of names.
583 * @param array $names An array of names
585 * @return array An array of abbreviations
587 public static function getAbbreviations($names)
590 foreach ($names as $name) {
591 for ($len = strlen($name); $len > 0; --$len) {
592 $abbrev = substr($name, 0, $len);
593 $abbrevs[$abbrev][] = $name;
601 * Returns a text representation of the Application.
603 * @param string $namespace An optional namespace name
604 * @param bool $raw Whether to return raw command list
606 * @return string A string representing the Application
608 * @deprecated since version 2.3, to be removed in 3.0.
610 public function asText($namespace = null, $raw = false)
612 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0.', E_USER_DEPRECATED);
614 $descriptor = new TextDescriptor();
615 $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, !$raw);
616 $descriptor->describe($output, $this, array('namespace' => $namespace, 'raw_output' => true));
618 return $output->fetch();
622 * Returns an XML representation of the Application.
624 * @param string $namespace An optional namespace name
625 * @param bool $asDom Whether to return a DOM or an XML string
627 * @return string|\DOMDocument An XML string representing the Application
629 * @deprecated since version 2.3, to be removed in 3.0.
631 public function asXml($namespace = null, $asDom = false)
633 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0.', E_USER_DEPRECATED);
635 $descriptor = new XmlDescriptor();
638 return $descriptor->getApplicationDocument($this, $namespace);
641 $output = new BufferedOutput();
642 $descriptor->describe($output, $this, array('namespace' => $namespace));
644 return $output->fetch();
648 * Renders a caught exception.
650 * @param \Exception $e An exception instance
651 * @param OutputInterface $output An OutputInterface instance
653 public function renderException($e, $output)
655 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
658 $title = sprintf(' [%s] ', get_class($e));
660 $len = Helper::strlen($title);
662 $width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
663 // 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
664 if (defined('HHVM_VERSION') && $width > 1 << 31) {
668 foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
669 foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
670 // pre-format lines to get the right string length
671 $lineLength = Helper::strlen($line) + 4;
672 $lines[] = array($line, $lineLength);
674 $len = max($lineLength, $len);
679 $messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
680 $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
681 foreach ($lines as $line) {
682 $messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
684 $messages[] = $emptyLine;
687 $output->writeln($messages, OutputInterface::VERBOSITY_QUIET);
689 if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
690 $output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
692 // exception related properties
693 $trace = $e->getTrace();
694 array_unshift($trace, array(
696 'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
697 'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
701 for ($i = 0, $count = count($trace); $i < $count; ++$i) {
702 $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
703 $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
704 $function = $trace[$i]['function'];
705 $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
706 $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
708 $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET);
711 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
713 } while ($e = $e->getPrevious());
715 if (null !== $this->runningCommand) {
716 $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
717 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
722 * Tries to figure out the terminal width in which this application runs.
726 protected function getTerminalWidth()
728 $dimensions = $this->getTerminalDimensions();
730 return $dimensions[0];
734 * Tries to figure out the terminal height in which this application runs.
738 protected function getTerminalHeight()
740 $dimensions = $this->getTerminalDimensions();
742 return $dimensions[1];
746 * Tries to figure out the terminal dimensions based on the current environment.
748 * @return array Array containing width and height
750 public function getTerminalDimensions()
752 if ($this->terminalDimensions) {
753 return $this->terminalDimensions;
756 if ('\\' === DIRECTORY_SEPARATOR) {
757 // extract [w, H] from "wxh (WxH)"
758 if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) {
759 return array((int) $matches[1], (int) $matches[2]);
761 // extract [w, h] from "wxh"
762 if (preg_match('/^(\d+)x(\d+)$/', $this->getConsoleMode(), $matches)) {
763 return array((int) $matches[1], (int) $matches[2]);
767 if ($sttyString = $this->getSttyColumns()) {
768 // extract [w, h] from "rows h; columns w;"
769 if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
770 return array((int) $matches[2], (int) $matches[1]);
772 // extract [w, h] from "; h rows; w columns"
773 if (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
774 return array((int) $matches[2], (int) $matches[1]);
778 return array(null, null);
782 * Sets terminal dimensions.
784 * Can be useful to force terminal dimensions for functional tests.
786 * @param int $width The width
787 * @param int $height The height
791 public function setTerminalDimensions($width, $height)
793 $this->terminalDimensions = array($width, $height);
799 * Configures the input and output instances based on the user arguments and options.
801 * @param InputInterface $input An InputInterface instance
802 * @param OutputInterface $output An OutputInterface instance
804 protected function configureIO(InputInterface $input, OutputInterface $output)
806 if (true === $input->hasParameterOption(array('--ansi'))) {
807 $output->setDecorated(true);
808 } elseif (true === $input->hasParameterOption(array('--no-ansi'))) {
809 $output->setDecorated(false);
812 if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
813 $input->setInteractive(false);
814 } elseif (function_exists('posix_isatty') && $this->getHelperSet()->has('question')) {
815 $inputStream = $this->getHelperSet()->get('question')->getInputStream();
816 if (!@posix_isatty($inputStream) && false === getenv('SHELL_INTERACTIVE')) {
817 $input->setInteractive(false);
821 if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
822 $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
823 $input->setInteractive(false);
825 if ($input->hasParameterOption('-vvv') || $input->hasParameterOption('--verbose=3') || $input->getParameterOption('--verbose') === 3) {
826 $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
827 } elseif ($input->hasParameterOption('-vv') || $input->hasParameterOption('--verbose=2') || $input->getParameterOption('--verbose') === 2) {
828 $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
829 } elseif ($input->hasParameterOption('-v') || $input->hasParameterOption('--verbose=1') || $input->hasParameterOption('--verbose') || $input->getParameterOption('--verbose')) {
830 $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
836 * Runs the current command.
838 * If an event dispatcher has been attached to the application,
839 * events are also dispatched during the life-cycle of the command.
841 * @param Command $command A Command instance
842 * @param InputInterface $input An Input instance
843 * @param OutputInterface $output An Output instance
845 * @return int 0 if everything went fine, or an error code
847 protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
849 foreach ($command->getHelperSet() as $helper) {
850 if ($helper instanceof InputAwareInterface) {
851 $helper->setInput($input);
855 if (null === $this->dispatcher) {
856 return $command->run($input, $output);
859 // bind before the console.command event, so the listeners have access to input options/arguments
861 $command->mergeApplicationDefinition();
862 $input->bind($command->getDefinition());
863 } catch (ExceptionInterface $e) {
864 // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
867 $event = new ConsoleCommandEvent($command, $input, $output);
871 $this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
873 if ($event->commandShouldRun()) {
874 $exitCode = $command->run($input, $output);
876 $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
878 } catch (\Exception $e) {
879 } catch (\Throwable $e) {
882 $x = $e instanceof \Exception ? $e : new FatalThrowableError($e);
883 $event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode());
884 $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
886 if ($x !== $event->getException()) {
887 $e = $event->getException();
889 $exitCode = $e->getCode();
892 $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
893 $this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
899 return $event->getExitCode();
903 * Gets the name of the command based on input.
905 * @param InputInterface $input The input interface
907 * @return string The command name
909 protected function getCommandName(InputInterface $input)
911 return $input->getFirstArgument();
915 * Gets the default input definition.
917 * @return InputDefinition An InputDefinition instance
919 protected function getDefaultInputDefinition()
921 return new InputDefinition(array(
922 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
924 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
925 new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
926 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'),
927 new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
928 new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
929 new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
930 new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
935 * Gets the default commands that should always be available.
937 * @return Command[] An array of default Command instances
939 protected function getDefaultCommands()
941 return array(new HelpCommand(), new ListCommand());
945 * Gets the default helper set with the helpers that should always be available.
947 * @return HelperSet A HelperSet instance
949 protected function getDefaultHelperSet()
951 return new HelperSet(array(
952 new FormatterHelper(),
953 new DialogHelper(false),
954 new ProgressHelper(false),
955 new TableHelper(false),
956 new DebugFormatterHelper(),
958 new QuestionHelper(),
963 * Runs and parses stty -a if it's available, suppressing any error output.
967 private function getSttyColumns()
969 if (!function_exists('proc_open')) {
973 $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
974 $process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
975 if (is_resource($process)) {
976 $info = stream_get_contents($pipes[1]);
979 proc_close($process);
986 * Runs and parses mode CON if it's available, suppressing any error output.
988 * @return string|null <width>x<height> or null if it could not be parsed
990 private function getConsoleMode()
992 if (!function_exists('proc_open')) {
996 $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
997 $process = proc_open('mode CON', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
998 if (is_resource($process)) {
999 $info = stream_get_contents($pipes[1]);
1002 proc_close($process);
1004 if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
1005 return $matches[2].'x'.$matches[1];
1011 * Returns abbreviated suggestions in string format.
1013 * @param array $abbrevs Abbreviated suggestions to convert
1015 * @return string A formatted string of abbreviated suggestions
1017 private function getAbbreviationSuggestions($abbrevs)
1019 return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
1023 * Returns the namespace part of the command name.
1025 * This method is not part of public API and should not be used directly.
1027 * @param string $name The full name of the command
1028 * @param string $limit The maximum number of parts of the namespace
1030 * @return string The namespace of the command
1032 public function extractNamespace($name, $limit = null)
1034 $parts = explode(':', $name);
1037 return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
1041 * Finds alternative of $name among $collection,
1042 * if nothing is found in $collection, try in $abbrevs.
1044 * @param string $name The string
1045 * @param array|\Traversable $collection The collection
1047 * @return string[] A sorted array of similar string
1049 private function findAlternatives($name, $collection)
1052 $alternatives = array();
1054 $collectionParts = array();
1055 foreach ($collection as $item) {
1056 $collectionParts[$item] = explode(':', $item);
1059 foreach (explode(':', $name) as $i => $subname) {
1060 foreach ($collectionParts as $collectionName => $parts) {
1061 $exists = isset($alternatives[$collectionName]);
1062 if (!isset($parts[$i]) && $exists) {
1063 $alternatives[$collectionName] += $threshold;
1065 } elseif (!isset($parts[$i])) {
1069 $lev = levenshtein($subname, $parts[$i]);
1070 if ($lev <= strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
1071 $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
1072 } elseif ($exists) {
1073 $alternatives[$collectionName] += $threshold;
1078 foreach ($collection as $item) {
1079 $lev = levenshtein($name, $item);
1080 if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
1081 $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
1085 $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
1086 asort($alternatives);
1088 return array_keys($alternatives);
1092 * Sets the default Command name.
1094 * @param string $commandName The Command name
1096 public function setDefaultCommand($commandName)
1098 $this->defaultCommand = $commandName;
1101 private function splitStringByWidth($string, $width)
1103 // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
1104 // additionally, array_slice() is not enough as some character has doubled width.
1105 // we need a function to split string not by character count but by string width
1106 if (false === $encoding = mb_detect_encoding($string, null, true)) {
1107 return str_split($string, $width);
1110 $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
1113 foreach (preg_split('//u', $utf8String) as $char) {
1114 // test if $char could be appended to current line
1115 if (mb_strwidth($line.$char, 'utf8') <= $width) {
1119 // if not, push current line to array and make new line
1120 $lines[] = str_pad($line, $width);
1124 $lines[] = count($lines) ? str_pad($line, $width) : $line;
1127 mb_convert_variables($encoding, 'utf8', $lines);
1133 * Returns all namespaces of the command name.
1135 * @param string $name The full name of the command
1137 * @return string[] The namespaces of the command
1139 private function extractAllNamespaces($name)
1141 // -1 as third argument is needed to skip the command short name when exploding
1142 $parts = explode(':', $name, -1);
1143 $namespaces = array();
1145 foreach ($parts as $part) {
1146 if (count($namespaces)) {
1147 $namespaces[] = end($namespaces).':'.$part;
1149 $namespaces[] = $part;