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\ProcessHelper;
20 use Symfony\Component\Console\Helper\QuestionHelper;
21 use Symfony\Component\Console\Input\InputInterface;
22 use Symfony\Component\Console\Input\ArgvInput;
23 use Symfony\Component\Console\Input\ArrayInput;
24 use Symfony\Component\Console\Input\InputDefinition;
25 use Symfony\Component\Console\Input\InputOption;
26 use Symfony\Component\Console\Input\InputArgument;
27 use Symfony\Component\Console\Input\InputAwareInterface;
28 use Symfony\Component\Console\Output\BufferedOutput;
29 use Symfony\Component\Console\Output\OutputInterface;
30 use Symfony\Component\Console\Output\ConsoleOutput;
31 use Symfony\Component\Console\Output\ConsoleOutputInterface;
32 use Symfony\Component\Console\Command\Command;
33 use Symfony\Component\Console\Command\HelpCommand;
34 use Symfony\Component\Console\Command\ListCommand;
35 use Symfony\Component\Console\Helper\HelperSet;
36 use Symfony\Component\Console\Helper\FormatterHelper;
37 use Symfony\Component\Console\Helper\DialogHelper;
38 use Symfony\Component\Console\Helper\ProgressHelper;
39 use Symfony\Component\Console\Helper\TableHelper;
40 use Symfony\Component\Console\Event\ConsoleCommandEvent;
41 use Symfony\Component\Console\Event\ConsoleExceptionEvent;
42 use Symfony\Component\Console\Event\ConsoleTerminateEvent;
43 use Symfony\Component\Console\Exception\CommandNotFoundException;
44 use Symfony\Component\Console\Exception\LogicException;
45 use Symfony\Component\Debug\Exception\FatalThrowableError;
46 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
49 * An Application is the container for a collection of commands.
51 * It is the main entry point of a Console application.
53 * This class is optimized for a standard CLI environment.
57 * $app = new Application('myapp', '1.0 (stable)');
58 * $app->add(new SimpleCommand());
61 * @author Fabien Potencier <fabien@symfony.com>
65 private $commands = array();
66 private $wantHelps = false;
67 private $runningCommand;
70 private $catchExceptions = true;
71 private $autoExit = true;
75 private $terminalDimensions;
76 private $defaultCommand;
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->defaultCommand = 'list';
89 $this->helperSet = $this->getDefaultHelperSet();
90 $this->definition = $this->getDefaultInputDefinition();
92 foreach ($this->getDefaultCommands() as $command) {
97 public function setDispatcher(EventDispatcherInterface $dispatcher)
99 $this->dispatcher = $dispatcher;
103 * Runs the current application.
105 * @param InputInterface $input An Input instance
106 * @param OutputInterface $output An Output instance
108 * @return int 0 if everything went fine, or an error code
110 public function run(InputInterface $input = null, OutputInterface $output = null)
112 if (null === $input) {
113 $input = new ArgvInput();
116 if (null === $output) {
117 $output = new ConsoleOutput();
120 $this->configureIO($input, $output);
123 $exitCode = $this->doRun($input, $output);
124 } catch (\Exception $e) {
125 if (!$this->catchExceptions) {
129 if ($output instanceof ConsoleOutputInterface) {
130 $this->renderException($e, $output->getErrorOutput());
132 $this->renderException($e, $output);
135 $exitCode = $e->getCode();
136 if (is_numeric($exitCode)) {
137 $exitCode = (int) $exitCode;
138 if (0 === $exitCode) {
146 if ($this->autoExit) {
147 if ($exitCode > 255) {
158 * Runs the current application.
160 * @param InputInterface $input An Input instance
161 * @param OutputInterface $output An Output instance
163 * @return int 0 if everything went fine, or an error code
165 public function doRun(InputInterface $input, OutputInterface $output)
167 if (true === $input->hasParameterOption(array('--version', '-V'))) {
168 $output->writeln($this->getLongVersion());
173 $name = $this->getCommandName($input);
174 if (true === $input->hasParameterOption(array('--help', '-h'))) {
177 $input = new ArrayInput(array('command' => 'help'));
179 $this->wantHelps = true;
184 $name = $this->defaultCommand;
185 $input = new ArrayInput(array('command' => $this->defaultCommand));
188 // the command name MUST be the first element of the input
189 $command = $this->find($name);
191 $this->runningCommand = $command;
192 $exitCode = $this->doRunCommand($command, $input, $output);
193 $this->runningCommand = null;
199 * Set a helper set to be used with the command.
201 * @param HelperSet $helperSet The helper set
203 public function setHelperSet(HelperSet $helperSet)
205 $this->helperSet = $helperSet;
209 * Get the helper set associated with the command.
211 * @return HelperSet The HelperSet instance associated with this command
213 public function getHelperSet()
215 return $this->helperSet;
219 * Set an input definition to be used with this application.
221 * @param InputDefinition $definition The input definition
223 public function setDefinition(InputDefinition $definition)
225 $this->definition = $definition;
229 * Gets the InputDefinition related to this Application.
231 * @return InputDefinition The InputDefinition instance
233 public function getDefinition()
235 return $this->definition;
239 * Gets the help message.
241 * @return string A help message
243 public function getHelp()
245 return $this->getLongVersion();
249 * Sets whether to catch exceptions or not during commands execution.
251 * @param bool $boolean Whether to catch exceptions or not during commands execution
253 public function setCatchExceptions($boolean)
255 $this->catchExceptions = (bool) $boolean;
259 * Sets whether to automatically exit after a command execution or not.
261 * @param bool $boolean Whether to automatically exit after a command execution or not
263 public function setAutoExit($boolean)
265 $this->autoExit = (bool) $boolean;
269 * Gets the name of the application.
271 * @return string The application name
273 public function getName()
279 * Sets the application name.
281 * @param string $name The application name
283 public function setName($name)
289 * Gets the application version.
291 * @return string The application version
293 public function getVersion()
295 return $this->version;
299 * Sets the application version.
301 * @param string $version The application version
303 public function setVersion($version)
305 $this->version = $version;
309 * Returns the long version of the application.
311 * @return string The long application version
313 public function getLongVersion()
315 if ('UNKNOWN' !== $this->getName()) {
316 if ('UNKNOWN' !== $this->getVersion()) {
317 return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
320 return sprintf('<info>%s</info>', $this->getName());
323 return '<info>Console Tool</info>';
327 * Registers a new command.
329 * @param string $name The command name
331 * @return Command The newly created command
333 public function register($name)
335 return $this->add(new Command($name));
339 * Adds an array of command objects.
341 * If a Command is not enabled it will not be added.
343 * @param Command[] $commands An array of commands
345 public function addCommands(array $commands)
347 foreach ($commands as $command) {
348 $this->add($command);
353 * Adds a command object.
355 * If a command with the same name already exists, it will be overridden.
356 * If the command is not enabled it will not be added.
358 * @param Command $command A Command object
360 * @return Command|null The registered command if enabled or null
362 public function add(Command $command)
364 $command->setApplication($this);
366 if (!$command->isEnabled()) {
367 $command->setApplication(null);
372 if (null === $command->getDefinition()) {
373 throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', get_class($command)));
376 $this->commands[$command->getName()] = $command;
378 foreach ($command->getAliases() as $alias) {
379 $this->commands[$alias] = $command;
386 * Returns a registered command by name or alias.
388 * @param string $name The command name or alias
390 * @return Command A Command object
392 * @throws CommandNotFoundException When given command name does not exist
394 public function get($name)
396 if (!isset($this->commands[$name])) {
397 throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name));
400 $command = $this->commands[$name];
402 if ($this->wantHelps) {
403 $this->wantHelps = false;
405 $helpCommand = $this->get('help');
406 $helpCommand->setCommand($command);
415 * Returns true if the command exists, false otherwise.
417 * @param string $name The command name or alias
419 * @return bool true if the command exists, false otherwise
421 public function has($name)
423 return isset($this->commands[$name]);
427 * Returns an array of all unique namespaces used by currently registered commands.
429 * It does not return the global namespace which always exists.
431 * @return string[] An array of namespaces
433 public function getNamespaces()
435 $namespaces = array();
436 foreach ($this->all() as $command) {
437 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
439 foreach ($command->getAliases() as $alias) {
440 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias));
444 return array_values(array_unique(array_filter($namespaces)));
448 * Finds a registered namespace by a name or an abbreviation.
450 * @param string $namespace A namespace or abbreviation to search for
452 * @return string A registered namespace
454 * @throws CommandNotFoundException When namespace is incorrect or ambiguous
456 public function findNamespace($namespace)
458 $allNamespaces = $this->getNamespaces();
459 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $namespace);
460 $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
462 if (empty($namespaces)) {
463 $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
465 if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
466 if (1 == count($alternatives)) {
467 $message .= "\n\nDid you mean this?\n ";
469 $message .= "\n\nDid you mean one of these?\n ";
472 $message .= implode("\n ", $alternatives);
475 throw new CommandNotFoundException($message, $alternatives);
478 $exact = in_array($namespace, $namespaces, true);
479 if (count($namespaces) > 1 && !$exact) {
480 throw new CommandNotFoundException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
483 return $exact ? $namespace : reset($namespaces);
487 * Finds a command by name or alias.
489 * Contrary to get, this command tries to find the best
490 * match if you give it an abbreviation of a name or alias.
492 * @param string $name A command name or a command alias
494 * @return Command A Command instance
496 * @throws CommandNotFoundException When command name is incorrect or ambiguous
498 public function find($name)
500 $allCommands = array_keys($this->commands);
501 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
502 $commands = preg_grep('{^'.$expr.'}', $allCommands);
504 if (empty($commands) || count(preg_grep('{^'.$expr.'$}', $commands)) < 1) {
505 if (false !== $pos = strrpos($name, ':')) {
506 // check if a namespace exists and contains commands
507 $this->findNamespace(substr($name, 0, $pos));
510 $message = sprintf('Command "%s" is not defined.', $name);
512 if ($alternatives = $this->findAlternatives($name, $allCommands)) {
513 if (1 == count($alternatives)) {
514 $message .= "\n\nDid you mean this?\n ";
516 $message .= "\n\nDid you mean one of these?\n ";
518 $message .= implode("\n ", $alternatives);
521 throw new CommandNotFoundException($message, $alternatives);
524 // filter out aliases for commands which are already on the list
525 if (count($commands) > 1) {
526 $commandList = $this->commands;
527 $commands = array_filter($commands, function ($nameOrAlias) use ($commandList, $commands) {
528 $commandName = $commandList[$nameOrAlias]->getName();
530 return $commandName === $nameOrAlias || !in_array($commandName, $commands);
534 $exact = in_array($name, $commands, true);
535 if (count($commands) > 1 && !$exact) {
536 $suggestions = $this->getAbbreviationSuggestions(array_values($commands));
538 throw new CommandNotFoundException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions), array_values($commands));
541 return $this->get($exact ? $name : reset($commands));
545 * Gets the commands (registered in the given namespace if provided).
547 * The array keys are the full names and the values the command instances.
549 * @param string $namespace A namespace name
551 * @return Command[] An array of Command instances
553 public function all($namespace = null)
555 if (null === $namespace) {
556 return $this->commands;
560 foreach ($this->commands as $name => $command) {
561 if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
562 $commands[$name] = $command;
570 * Returns an array of possible abbreviations given a set of names.
572 * @param array $names An array of names
574 * @return array An array of abbreviations
576 public static function getAbbreviations($names)
579 foreach ($names as $name) {
580 for ($len = strlen($name); $len > 0; --$len) {
581 $abbrev = substr($name, 0, $len);
582 $abbrevs[$abbrev][] = $name;
590 * Returns a text representation of the Application.
592 * @param string $namespace An optional namespace name
593 * @param bool $raw Whether to return raw command list
595 * @return string A string representing the Application
597 * @deprecated since version 2.3, to be removed in 3.0.
599 public function asText($namespace = null, $raw = false)
601 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0.', E_USER_DEPRECATED);
603 $descriptor = new TextDescriptor();
604 $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, !$raw);
605 $descriptor->describe($output, $this, array('namespace' => $namespace, 'raw_output' => true));
607 return $output->fetch();
611 * Returns an XML representation of the Application.
613 * @param string $namespace An optional namespace name
614 * @param bool $asDom Whether to return a DOM or an XML string
616 * @return string|\DOMDocument An XML string representing the Application
618 * @deprecated since version 2.3, to be removed in 3.0.
620 public function asXml($namespace = null, $asDom = false)
622 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.3 and will be removed in 3.0.', E_USER_DEPRECATED);
624 $descriptor = new XmlDescriptor();
627 return $descriptor->getApplicationDocument($this, $namespace);
630 $output = new BufferedOutput();
631 $descriptor->describe($output, $this, array('namespace' => $namespace));
633 return $output->fetch();
637 * Renders a caught exception.
639 * @param \Exception $e An exception instance
640 * @param OutputInterface $output An OutputInterface instance
642 public function renderException($e, $output)
644 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
647 $title = sprintf(' [%s] ', get_class($e));
649 $len = $this->stringWidth($title);
651 $width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
652 // 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
653 if (defined('HHVM_VERSION') && $width > 1 << 31) {
657 foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
658 foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
659 // pre-format lines to get the right string length
660 $lineLength = $this->stringWidth($line) + 4;
661 $lines[] = array($line, $lineLength);
663 $len = max($lineLength, $len);
668 $messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
669 $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - $this->stringWidth($title))));
670 foreach ($lines as $line) {
671 $messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
673 $messages[] = $emptyLine;
676 $output->writeln($messages, OutputInterface::VERBOSITY_QUIET);
678 if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
679 $output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
681 // exception related properties
682 $trace = $e->getTrace();
683 array_unshift($trace, array(
685 'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
686 'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
690 for ($i = 0, $count = count($trace); $i < $count; ++$i) {
691 $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
692 $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
693 $function = $trace[$i]['function'];
694 $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
695 $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
697 $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET);
700 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
702 } while ($e = $e->getPrevious());
704 if (null !== $this->runningCommand) {
705 $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
706 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
711 * Tries to figure out the terminal width in which this application runs.
715 protected function getTerminalWidth()
717 $dimensions = $this->getTerminalDimensions();
719 return $dimensions[0];
723 * Tries to figure out the terminal height in which this application runs.
727 protected function getTerminalHeight()
729 $dimensions = $this->getTerminalDimensions();
731 return $dimensions[1];
735 * Tries to figure out the terminal dimensions based on the current environment.
737 * @return array Array containing width and height
739 public function getTerminalDimensions()
741 if ($this->terminalDimensions) {
742 return $this->terminalDimensions;
745 if ('\\' === DIRECTORY_SEPARATOR) {
746 // extract [w, H] from "wxh (WxH)"
747 if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) {
748 return array((int) $matches[1], (int) $matches[2]);
750 // extract [w, h] from "wxh"
751 if (preg_match('/^(\d+)x(\d+)$/', $this->getConsoleMode(), $matches)) {
752 return array((int) $matches[1], (int) $matches[2]);
756 if ($sttyString = $this->getSttyColumns()) {
757 // extract [w, h] from "rows h; columns w;"
758 if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
759 return array((int) $matches[2], (int) $matches[1]);
761 // extract [w, h] from "; h rows; w columns"
762 if (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
763 return array((int) $matches[2], (int) $matches[1]);
767 return array(null, null);
771 * Sets terminal dimensions.
773 * Can be useful to force terminal dimensions for functional tests.
775 * @param int $width The width
776 * @param int $height The height
780 public function setTerminalDimensions($width, $height)
782 $this->terminalDimensions = array($width, $height);
788 * Configures the input and output instances based on the user arguments and options.
790 * @param InputInterface $input An InputInterface instance
791 * @param OutputInterface $output An OutputInterface instance
793 protected function configureIO(InputInterface $input, OutputInterface $output)
795 if (true === $input->hasParameterOption(array('--ansi'))) {
796 $output->setDecorated(true);
797 } elseif (true === $input->hasParameterOption(array('--no-ansi'))) {
798 $output->setDecorated(false);
801 if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
802 $input->setInteractive(false);
803 } elseif (function_exists('posix_isatty') && $this->getHelperSet()->has('question')) {
804 $inputStream = $this->getHelperSet()->get('question')->getInputStream();
805 if (!@posix_isatty($inputStream) && false === getenv('SHELL_INTERACTIVE')) {
806 $input->setInteractive(false);
810 if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
811 $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
812 $input->setInteractive(false);
814 if ($input->hasParameterOption('-vvv') || $input->hasParameterOption('--verbose=3') || $input->getParameterOption('--verbose') === 3) {
815 $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
816 } elseif ($input->hasParameterOption('-vv') || $input->hasParameterOption('--verbose=2') || $input->getParameterOption('--verbose') === 2) {
817 $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
818 } elseif ($input->hasParameterOption('-v') || $input->hasParameterOption('--verbose=1') || $input->hasParameterOption('--verbose') || $input->getParameterOption('--verbose')) {
819 $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
825 * Runs the current command.
827 * If an event dispatcher has been attached to the application,
828 * events are also dispatched during the life-cycle of the command.
830 * @param Command $command A Command instance
831 * @param InputInterface $input An Input instance
832 * @param OutputInterface $output An Output instance
834 * @return int 0 if everything went fine, or an error code
836 protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
838 foreach ($command->getHelperSet() as $helper) {
839 if ($helper instanceof InputAwareInterface) {
840 $helper->setInput($input);
844 if (null === $this->dispatcher) {
846 return $command->run($input, $output);
847 } catch (\Exception $e) {
849 } catch (\Throwable $e) {
850 throw new FatalThrowableError($e);
854 // bind before the console.command event, so the listeners have access to input options/arguments
856 $command->mergeApplicationDefinition();
857 $input->bind($command->getDefinition());
858 } catch (ExceptionInterface $e) {
859 // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
862 $event = new ConsoleCommandEvent($command, $input, $output);
863 $this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
865 if ($event->commandShouldRun()) {
868 $exitCode = $command->run($input, $output);
869 } catch (\Exception $x) {
871 } catch (\Throwable $x) {
872 $e = new FatalThrowableError($x);
875 $event = new ConsoleExceptionEvent($command, $input, $output, $e, $e->getCode());
876 $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
878 if ($e !== $event->getException()) {
879 $x = $e = $event->getException();
882 $event = new ConsoleTerminateEvent($command, $input, $output, $e->getCode());
883 $this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
888 $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
891 $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
892 $this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
894 return $event->getExitCode();
898 * Gets the name of the command based on input.
900 * @param InputInterface $input The input interface
902 * @return string The command name
904 protected function getCommandName(InputInterface $input)
906 return $input->getFirstArgument();
910 * Gets the default input definition.
912 * @return InputDefinition An InputDefinition instance
914 protected function getDefaultInputDefinition()
916 return new InputDefinition(array(
917 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
919 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
920 new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
921 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'),
922 new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
923 new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
924 new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
925 new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
930 * Gets the default commands that should always be available.
932 * @return Command[] An array of default Command instances
934 protected function getDefaultCommands()
936 return array(new HelpCommand(), new ListCommand());
940 * Gets the default helper set with the helpers that should always be available.
942 * @return HelperSet A HelperSet instance
944 protected function getDefaultHelperSet()
946 return new HelperSet(array(
947 new FormatterHelper(),
948 new DialogHelper(false),
949 new ProgressHelper(false),
950 new TableHelper(false),
951 new DebugFormatterHelper(),
953 new QuestionHelper(),
958 * Runs and parses stty -a if it's available, suppressing any error output.
962 private function getSttyColumns()
964 if (!function_exists('proc_open')) {
968 $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
969 $process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
970 if (is_resource($process)) {
971 $info = stream_get_contents($pipes[1]);
974 proc_close($process);
981 * Runs and parses mode CON if it's available, suppressing any error output.
983 * @return string|null <width>x<height> or null if it could not be parsed
985 private function getConsoleMode()
987 if (!function_exists('proc_open')) {
991 $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
992 $process = proc_open('mode CON', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
993 if (is_resource($process)) {
994 $info = stream_get_contents($pipes[1]);
997 proc_close($process);
999 if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
1000 return $matches[2].'x'.$matches[1];
1006 * Returns abbreviated suggestions in string format.
1008 * @param array $abbrevs Abbreviated suggestions to convert
1010 * @return string A formatted string of abbreviated suggestions
1012 private function getAbbreviationSuggestions($abbrevs)
1014 return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
1018 * Returns the namespace part of the command name.
1020 * This method is not part of public API and should not be used directly.
1022 * @param string $name The full name of the command
1023 * @param string $limit The maximum number of parts of the namespace
1025 * @return string The namespace of the command
1027 public function extractNamespace($name, $limit = null)
1029 $parts = explode(':', $name);
1032 return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
1036 * Finds alternative of $name among $collection,
1037 * if nothing is found in $collection, try in $abbrevs.
1039 * @param string $name The string
1040 * @param array|\Traversable $collection The collection
1042 * @return string[] A sorted array of similar string
1044 private function findAlternatives($name, $collection)
1047 $alternatives = array();
1049 $collectionParts = array();
1050 foreach ($collection as $item) {
1051 $collectionParts[$item] = explode(':', $item);
1054 foreach (explode(':', $name) as $i => $subname) {
1055 foreach ($collectionParts as $collectionName => $parts) {
1056 $exists = isset($alternatives[$collectionName]);
1057 if (!isset($parts[$i]) && $exists) {
1058 $alternatives[$collectionName] += $threshold;
1060 } elseif (!isset($parts[$i])) {
1064 $lev = levenshtein($subname, $parts[$i]);
1065 if ($lev <= strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
1066 $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
1067 } elseif ($exists) {
1068 $alternatives[$collectionName] += $threshold;
1073 foreach ($collection as $item) {
1074 $lev = levenshtein($name, $item);
1075 if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
1076 $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
1080 $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
1081 asort($alternatives);
1083 return array_keys($alternatives);
1087 * Sets the default Command name.
1089 * @param string $commandName The Command name
1091 public function setDefaultCommand($commandName)
1093 $this->defaultCommand = $commandName;
1096 private function stringWidth($string)
1098 if (false === $encoding = mb_detect_encoding($string, null, true)) {
1099 return strlen($string);
1102 return mb_strwidth($string, $encoding);
1105 private function splitStringByWidth($string, $width)
1107 // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
1108 // additionally, array_slice() is not enough as some character has doubled width.
1109 // we need a function to split string not by character count but by string width
1110 if (false === $encoding = mb_detect_encoding($string, null, true)) {
1111 return str_split($string, $width);
1114 $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
1117 foreach (preg_split('//u', $utf8String) as $char) {
1118 // test if $char could be appended to current line
1119 if (mb_strwidth($line.$char, 'utf8') <= $width) {
1123 // if not, push current line to array and make new line
1124 $lines[] = str_pad($line, $width);
1128 $lines[] = count($lines) ? str_pad($line, $width) : $line;
1131 mb_convert_variables($encoding, 'utf8', $lines);
1137 * Returns all namespaces of the command name.
1139 * @param string $name The full name of the command
1141 * @return string[] The namespaces of the command
1143 private function extractAllNamespaces($name)
1145 // -1 as third argument is needed to skip the command short name when exploding
1146 $parts = explode(':', $name, -1);
1147 $namespaces = array();
1149 foreach ($parts as $part) {
1150 if (count($namespaces)) {
1151 $namespaces[] = end($namespaces).':'.$part;
1153 $namespaces[] = $part;