composer package updates
[openemr.git] / vendor / symfony / console / Application.php
blob1e447fa20a2398edbc5fe5be8fd0c18b0e496209
1 <?php
3 /*
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\Exception\ExceptionInterface;
15 use Symfony\Component\Console\Formatter\OutputFormatter;
16 use Symfony\Component\Console\Helper\DebugFormatterHelper;
17 use Symfony\Component\Console\Helper\Helper;
18 use Symfony\Component\Console\Helper\ProcessHelper;
19 use Symfony\Component\Console\Helper\QuestionHelper;
20 use Symfony\Component\Console\Input\InputInterface;
21 use Symfony\Component\Console\Input\StreamableInputInterface;
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\OutputInterface;
29 use Symfony\Component\Console\Output\ConsoleOutput;
30 use Symfony\Component\Console\Output\ConsoleOutputInterface;
31 use Symfony\Component\Console\Command\Command;
32 use Symfony\Component\Console\Command\HelpCommand;
33 use Symfony\Component\Console\Command\ListCommand;
34 use Symfony\Component\Console\Helper\HelperSet;
35 use Symfony\Component\Console\Helper\FormatterHelper;
36 use Symfony\Component\Console\Event\ConsoleCommandEvent;
37 use Symfony\Component\Console\Event\ConsoleExceptionEvent;
38 use Symfony\Component\Console\Event\ConsoleTerminateEvent;
39 use Symfony\Component\Console\Exception\CommandNotFoundException;
40 use Symfony\Component\Console\Exception\LogicException;
41 use Symfony\Component\Debug\Exception\FatalThrowableError;
42 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
44 /**
45 * An Application is the container for a collection of commands.
47 * It is the main entry point of a Console application.
49 * This class is optimized for a standard CLI environment.
51 * Usage:
53 * $app = new Application('myapp', '1.0 (stable)');
54 * $app->add(new SimpleCommand());
55 * $app->run();
57 * @author Fabien Potencier <fabien@symfony.com>
59 class Application
61 private $commands = array();
62 private $wantHelps = false;
63 private $runningCommand;
64 private $name;
65 private $version;
66 private $catchExceptions = true;
67 private $autoExit = true;
68 private $definition;
69 private $helperSet;
70 private $dispatcher;
71 private $terminal;
72 private $defaultCommand;
73 private $singleCommand;
75 /**
76 * @param string $name The name of the application
77 * @param string $version The version of the application
79 public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
81 $this->name = $name;
82 $this->version = $version;
83 $this->terminal = new Terminal();
84 $this->defaultCommand = 'list';
85 $this->helperSet = $this->getDefaultHelperSet();
86 $this->definition = $this->getDefaultInputDefinition();
88 foreach ($this->getDefaultCommands() as $command) {
89 $this->add($command);
93 public function setDispatcher(EventDispatcherInterface $dispatcher)
95 $this->dispatcher = $dispatcher;
98 /**
99 * Runs the current application.
101 * @param InputInterface $input An Input instance
102 * @param OutputInterface $output An Output instance
104 * @return int 0 if everything went fine, or an error code
106 * @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}.
108 public function run(InputInterface $input = null, OutputInterface $output = null)
110 putenv('LINES='.$this->terminal->getHeight());
111 putenv('COLUMNS='.$this->terminal->getWidth());
113 if (null === $input) {
114 $input = new ArgvInput();
117 if (null === $output) {
118 $output = new ConsoleOutput();
121 $this->configureIO($input, $output);
123 try {
124 $e = null;
125 $exitCode = $this->doRun($input, $output);
126 } catch (\Exception $x) {
127 $e = $x;
128 } catch (\Throwable $x) {
129 $e = new FatalThrowableError($x);
132 if (null !== $e) {
133 if (!$this->catchExceptions || !$x instanceof \Exception) {
134 throw $x;
137 if ($output instanceof ConsoleOutputInterface) {
138 $this->renderException($e, $output->getErrorOutput());
139 } else {
140 $this->renderException($e, $output);
143 $exitCode = $e->getCode();
144 if (is_numeric($exitCode)) {
145 $exitCode = (int) $exitCode;
146 if (0 === $exitCode) {
147 $exitCode = 1;
149 } else {
150 $exitCode = 1;
154 if ($this->autoExit) {
155 if ($exitCode > 255) {
156 $exitCode = 255;
159 exit($exitCode);
162 return $exitCode;
166 * Runs the current application.
168 * @param InputInterface $input An Input instance
169 * @param OutputInterface $output An Output instance
171 * @return int 0 if everything went fine, or an error code
173 public function doRun(InputInterface $input, OutputInterface $output)
175 if (true === $input->hasParameterOption(array('--version', '-V'), true)) {
176 $output->writeln($this->getLongVersion());
178 return 0;
181 $name = $this->getCommandName($input);
182 if (true === $input->hasParameterOption(array('--help', '-h'), true)) {
183 if (!$name) {
184 $name = 'help';
185 $input = new ArrayInput(array('command_name' => $this->defaultCommand));
186 } else {
187 $this->wantHelps = true;
191 if (!$name) {
192 $name = $this->defaultCommand;
193 $this->definition->setArguments(array_merge(
194 $this->definition->getArguments(),
195 array(
196 'command' => new InputArgument('command', InputArgument::OPTIONAL, $this->definition->getArgument('command')->getDescription(), $name),
201 $this->runningCommand = null;
202 // the command name MUST be the first element of the input
203 $command = $this->find($name);
205 $this->runningCommand = $command;
206 $exitCode = $this->doRunCommand($command, $input, $output);
207 $this->runningCommand = null;
209 return $exitCode;
213 * Set a helper set to be used with the command.
215 * @param HelperSet $helperSet The helper set
217 public function setHelperSet(HelperSet $helperSet)
219 $this->helperSet = $helperSet;
223 * Get the helper set associated with the command.
225 * @return HelperSet The HelperSet instance associated with this command
227 public function getHelperSet()
229 return $this->helperSet;
233 * Set an input definition to be used with this application.
235 * @param InputDefinition $definition The input definition
237 public function setDefinition(InputDefinition $definition)
239 $this->definition = $definition;
243 * Gets the InputDefinition related to this Application.
245 * @return InputDefinition The InputDefinition instance
247 public function getDefinition()
249 if ($this->singleCommand) {
250 $inputDefinition = $this->definition;
251 $inputDefinition->setArguments();
253 return $inputDefinition;
256 return $this->definition;
260 * Gets the help message.
262 * @return string A help message
264 public function getHelp()
266 return $this->getLongVersion();
270 * Gets whether to catch exceptions or not during commands execution.
272 * @return bool Whether to catch exceptions or not during commands execution
274 public function areExceptionsCaught()
276 return $this->catchExceptions;
280 * Sets whether to catch exceptions or not during commands execution.
282 * @param bool $boolean Whether to catch exceptions or not during commands execution
284 public function setCatchExceptions($boolean)
286 $this->catchExceptions = (bool) $boolean;
290 * Gets whether to automatically exit after a command execution or not.
292 * @return bool Whether to automatically exit after a command execution or not
294 public function isAutoExitEnabled()
296 return $this->autoExit;
300 * Sets whether to automatically exit after a command execution or not.
302 * @param bool $boolean Whether to automatically exit after a command execution or not
304 public function setAutoExit($boolean)
306 $this->autoExit = (bool) $boolean;
310 * Gets the name of the application.
312 * @return string The application name
314 public function getName()
316 return $this->name;
320 * Sets the application name.
322 * @param string $name The application name
324 public function setName($name)
326 $this->name = $name;
330 * Gets the application version.
332 * @return string The application version
334 public function getVersion()
336 return $this->version;
340 * Sets the application version.
342 * @param string $version The application version
344 public function setVersion($version)
346 $this->version = $version;
350 * Returns the long version of the application.
352 * @return string The long application version
354 public function getLongVersion()
356 if ('UNKNOWN' !== $this->getName()) {
357 if ('UNKNOWN' !== $this->getVersion()) {
358 return sprintf('%s <info>%s</info>', $this->getName(), $this->getVersion());
361 return $this->getName();
364 return 'Console Tool';
368 * Registers a new command.
370 * @param string $name The command name
372 * @return Command The newly created command
374 public function register($name)
376 return $this->add(new Command($name));
380 * Adds an array of command objects.
382 * If a Command is not enabled it will not be added.
384 * @param Command[] $commands An array of commands
386 public function addCommands(array $commands)
388 foreach ($commands as $command) {
389 $this->add($command);
394 * Adds a command object.
396 * If a command with the same name already exists, it will be overridden.
397 * If the command is not enabled it will not be added.
399 * @param Command $command A Command object
401 * @return Command|null The registered command if enabled or null
403 public function add(Command $command)
405 $command->setApplication($this);
407 if (!$command->isEnabled()) {
408 $command->setApplication(null);
410 return;
413 if (null === $command->getDefinition()) {
414 throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', get_class($command)));
417 $this->commands[$command->getName()] = $command;
419 foreach ($command->getAliases() as $alias) {
420 $this->commands[$alias] = $command;
423 return $command;
427 * Returns a registered command by name or alias.
429 * @param string $name The command name or alias
431 * @return Command A Command object
433 * @throws CommandNotFoundException When given command name does not exist
435 public function get($name)
437 if (!isset($this->commands[$name])) {
438 throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name));
441 $command = $this->commands[$name];
443 if ($this->wantHelps) {
444 $this->wantHelps = false;
446 $helpCommand = $this->get('help');
447 $helpCommand->setCommand($command);
449 return $helpCommand;
452 return $command;
456 * Returns true if the command exists, false otherwise.
458 * @param string $name The command name or alias
460 * @return bool true if the command exists, false otherwise
462 public function has($name)
464 return isset($this->commands[$name]);
468 * Returns an array of all unique namespaces used by currently registered commands.
470 * It does not return the global namespace which always exists.
472 * @return string[] An array of namespaces
474 public function getNamespaces()
476 $namespaces = array();
477 foreach ($this->all() as $command) {
478 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
480 foreach ($command->getAliases() as $alias) {
481 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias));
485 return array_values(array_unique(array_filter($namespaces)));
489 * Finds a registered namespace by a name or an abbreviation.
491 * @param string $namespace A namespace or abbreviation to search for
493 * @return string A registered namespace
495 * @throws CommandNotFoundException When namespace is incorrect or ambiguous
497 public function findNamespace($namespace)
499 $allNamespaces = $this->getNamespaces();
500 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $namespace);
501 $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
503 if (empty($namespaces)) {
504 $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
506 if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
507 if (1 == count($alternatives)) {
508 $message .= "\n\nDid you mean this?\n ";
509 } else {
510 $message .= "\n\nDid you mean one of these?\n ";
513 $message .= implode("\n ", $alternatives);
516 throw new CommandNotFoundException($message, $alternatives);
519 $exact = in_array($namespace, $namespaces, true);
520 if (count($namespaces) > 1 && !$exact) {
521 throw new CommandNotFoundException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
524 return $exact ? $namespace : reset($namespaces);
528 * Finds a command by name or alias.
530 * Contrary to get, this command tries to find the best
531 * match if you give it an abbreviation of a name or alias.
533 * @param string $name A command name or a command alias
535 * @return Command A Command instance
537 * @throws CommandNotFoundException When command name is incorrect or ambiguous
539 public function find($name)
541 $allCommands = array_keys($this->commands);
542 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
543 $commands = preg_grep('{^'.$expr.'}', $allCommands);
545 if (empty($commands) || count(preg_grep('{^'.$expr.'$}', $commands)) < 1) {
546 if (false !== $pos = strrpos($name, ':')) {
547 // check if a namespace exists and contains commands
548 $this->findNamespace(substr($name, 0, $pos));
551 $message = sprintf('Command "%s" is not defined.', $name);
553 if ($alternatives = $this->findAlternatives($name, $allCommands)) {
554 if (1 == count($alternatives)) {
555 $message .= "\n\nDid you mean this?\n ";
556 } else {
557 $message .= "\n\nDid you mean one of these?\n ";
559 $message .= implode("\n ", $alternatives);
562 throw new CommandNotFoundException($message, $alternatives);
565 // filter out aliases for commands which are already on the list
566 if (count($commands) > 1) {
567 $commandList = $this->commands;
568 $commands = array_filter($commands, function ($nameOrAlias) use ($commandList, $commands) {
569 $commandName = $commandList[$nameOrAlias]->getName();
571 return $commandName === $nameOrAlias || !in_array($commandName, $commands);
575 $exact = in_array($name, $commands, true);
576 if (count($commands) > 1 && !$exact) {
577 $suggestions = $this->getAbbreviationSuggestions(array_values($commands));
579 throw new CommandNotFoundException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions), array_values($commands));
582 return $this->get($exact ? $name : reset($commands));
586 * Gets the commands (registered in the given namespace if provided).
588 * The array keys are the full names and the values the command instances.
590 * @param string $namespace A namespace name
592 * @return Command[] An array of Command instances
594 public function all($namespace = null)
596 if (null === $namespace) {
597 return $this->commands;
600 $commands = array();
601 foreach ($this->commands as $name => $command) {
602 if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
603 $commands[$name] = $command;
607 return $commands;
611 * Returns an array of possible abbreviations given a set of names.
613 * @param array $names An array of names
615 * @return array An array of abbreviations
617 public static function getAbbreviations($names)
619 $abbrevs = array();
620 foreach ($names as $name) {
621 for ($len = strlen($name); $len > 0; --$len) {
622 $abbrev = substr($name, 0, $len);
623 $abbrevs[$abbrev][] = $name;
627 return $abbrevs;
631 * Renders a caught exception.
633 * @param \Exception $e An exception instance
634 * @param OutputInterface $output An OutputInterface instance
636 public function renderException(\Exception $e, OutputInterface $output)
638 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
640 do {
641 $title = sprintf(
642 ' [%s%s] ',
643 get_class($e),
644 $output->isVerbose() && 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : ''
647 $len = Helper::strlen($title);
649 $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX;
650 // 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
651 if (defined('HHVM_VERSION') && $width > 1 << 31) {
652 $width = 1 << 31;
654 $lines = array();
655 foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
656 foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
657 // pre-format lines to get the right string length
658 $lineLength = Helper::strlen($line) + 4;
659 $lines[] = array($line, $lineLength);
661 $len = max($lineLength, $len);
665 $messages = array();
666 $messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
667 $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
668 foreach ($lines as $line) {
669 $messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
671 $messages[] = $emptyLine;
672 $messages[] = '';
674 $output->writeln($messages, OutputInterface::VERBOSITY_QUIET);
676 if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
677 $output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
679 // exception related properties
680 $trace = $e->getTrace();
681 array_unshift($trace, array(
682 'function' => '',
683 'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
684 'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
685 'args' => array(),
688 for ($i = 0, $count = count($trace); $i < $count; ++$i) {
689 $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
690 $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
691 $function = $trace[$i]['function'];
692 $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
693 $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
695 $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET);
698 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
700 } while ($e = $e->getPrevious());
702 if (null !== $this->runningCommand) {
703 $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
704 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
709 * Tries to figure out the terminal width in which this application runs.
711 * @return int|null
713 * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead.
715 protected function getTerminalWidth()
717 @trigger_error(sprintf('%s is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), E_USER_DEPRECATED);
719 return $this->terminal->getWidth();
723 * Tries to figure out the terminal height in which this application runs.
725 * @return int|null
727 * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead.
729 protected function getTerminalHeight()
731 @trigger_error(sprintf('%s is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), E_USER_DEPRECATED);
733 return $this->terminal->getHeight();
737 * Tries to figure out the terminal dimensions based on the current environment.
739 * @return array Array containing width and height
741 * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead.
743 public function getTerminalDimensions()
745 @trigger_error(sprintf('%s is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), E_USER_DEPRECATED);
747 return array($this->terminal->getWidth(), $this->terminal->getHeight());
751 * Sets terminal dimensions.
753 * Can be useful to force terminal dimensions for functional tests.
755 * @param int $width The width
756 * @param int $height The height
758 * @return $this
760 * @deprecated since version 3.2, to be removed in 4.0. Set the COLUMNS and LINES env vars instead.
762 public function setTerminalDimensions($width, $height)
764 @trigger_error(sprintf('%s 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);
766 putenv('COLUMNS='.$width);
767 putenv('LINES='.$height);
769 return $this;
773 * Configures the input and output instances based on the user arguments and options.
775 * @param InputInterface $input An InputInterface instance
776 * @param OutputInterface $output An OutputInterface instance
778 protected function configureIO(InputInterface $input, OutputInterface $output)
780 if (true === $input->hasParameterOption(array('--ansi'), true)) {
781 $output->setDecorated(true);
782 } elseif (true === $input->hasParameterOption(array('--no-ansi'), true)) {
783 $output->setDecorated(false);
786 if (true === $input->hasParameterOption(array('--no-interaction', '-n'), true)) {
787 $input->setInteractive(false);
788 } elseif (function_exists('posix_isatty')) {
789 $inputStream = null;
791 if ($input instanceof StreamableInputInterface) {
792 $inputStream = $input->getStream();
795 // This check ensures that calling QuestionHelper::setInputStream() works
796 // To be removed in 4.0 (in the same time as QuestionHelper::setInputStream)
797 if (!$inputStream && $this->getHelperSet()->has('question')) {
798 $inputStream = $this->getHelperSet()->get('question')->getInputStream(false);
801 if (!@posix_isatty($inputStream) && false === getenv('SHELL_INTERACTIVE')) {
802 $input->setInteractive(false);
806 if (true === $input->hasParameterOption(array('--quiet', '-q'), true)) {
807 $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
808 $input->setInteractive(false);
809 } else {
810 if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || $input->getParameterOption('--verbose', false, true) === 3) {
811 $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
812 } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || $input->getParameterOption('--verbose', false, true) === 2) {
813 $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
814 } elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) {
815 $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
821 * Runs the current command.
823 * If an event dispatcher has been attached to the application,
824 * events are also dispatched during the life-cycle of the command.
826 * @param Command $command A Command instance
827 * @param InputInterface $input An Input instance
828 * @param OutputInterface $output An Output instance
830 * @return int 0 if everything went fine, or an error code
832 protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
834 foreach ($command->getHelperSet() as $helper) {
835 if ($helper instanceof InputAwareInterface) {
836 $helper->setInput($input);
840 if (null === $this->dispatcher) {
841 return $command->run($input, $output);
844 // bind before the console.command event, so the listeners have access to input options/arguments
845 try {
846 $command->mergeApplicationDefinition();
847 $input->bind($command->getDefinition());
848 } catch (ExceptionInterface $e) {
849 // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
852 $event = new ConsoleCommandEvent($command, $input, $output);
853 $e = null;
855 try {
856 $this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
858 if ($event->commandShouldRun()) {
859 $exitCode = $command->run($input, $output);
860 } else {
861 $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
863 } catch (\Exception $e) {
864 } catch (\Throwable $e) {
866 if (null !== $e) {
867 $x = $e instanceof \Exception ? $e : new FatalThrowableError($e);
868 $event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode());
869 $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
871 if ($x !== $event->getException()) {
872 $e = $event->getException();
874 $exitCode = $e->getCode();
877 $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
878 $this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
880 if (null !== $e) {
881 throw $e;
884 return $event->getExitCode();
888 * Gets the name of the command based on input.
890 * @param InputInterface $input The input interface
892 * @return string The command name
894 protected function getCommandName(InputInterface $input)
896 return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument();
900 * Gets the default input definition.
902 * @return InputDefinition An InputDefinition instance
904 protected function getDefaultInputDefinition()
906 return new InputDefinition(array(
907 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
909 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
910 new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
911 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'),
912 new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
913 new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
914 new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
915 new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
920 * Gets the default commands that should always be available.
922 * @return Command[] An array of default Command instances
924 protected function getDefaultCommands()
926 return array(new HelpCommand(), new ListCommand());
930 * Gets the default helper set with the helpers that should always be available.
932 * @return HelperSet A HelperSet instance
934 protected function getDefaultHelperSet()
936 return new HelperSet(array(
937 new FormatterHelper(),
938 new DebugFormatterHelper(),
939 new ProcessHelper(),
940 new QuestionHelper(),
945 * Returns abbreviated suggestions in string format.
947 * @param array $abbrevs Abbreviated suggestions to convert
949 * @return string A formatted string of abbreviated suggestions
951 private function getAbbreviationSuggestions($abbrevs)
953 return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
957 * Returns the namespace part of the command name.
959 * This method is not part of public API and should not be used directly.
961 * @param string $name The full name of the command
962 * @param string $limit The maximum number of parts of the namespace
964 * @return string The namespace of the command
966 public function extractNamespace($name, $limit = null)
968 $parts = explode(':', $name);
969 array_pop($parts);
971 return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
975 * Finds alternative of $name among $collection,
976 * if nothing is found in $collection, try in $abbrevs.
978 * @param string $name The string
979 * @param array|\Traversable $collection The collection
981 * @return string[] A sorted array of similar string
983 private function findAlternatives($name, $collection)
985 $threshold = 1e3;
986 $alternatives = array();
988 $collectionParts = array();
989 foreach ($collection as $item) {
990 $collectionParts[$item] = explode(':', $item);
993 foreach (explode(':', $name) as $i => $subname) {
994 foreach ($collectionParts as $collectionName => $parts) {
995 $exists = isset($alternatives[$collectionName]);
996 if (!isset($parts[$i]) && $exists) {
997 $alternatives[$collectionName] += $threshold;
998 continue;
999 } elseif (!isset($parts[$i])) {
1000 continue;
1003 $lev = levenshtein($subname, $parts[$i]);
1004 if ($lev <= strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
1005 $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
1006 } elseif ($exists) {
1007 $alternatives[$collectionName] += $threshold;
1012 foreach ($collection as $item) {
1013 $lev = levenshtein($name, $item);
1014 if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
1015 $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
1019 $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
1020 asort($alternatives);
1022 return array_keys($alternatives);
1026 * Sets the default Command name.
1028 * @param string $commandName The Command name
1029 * @param bool $isSingleCommand Set to true if there is only one command in this application
1031 * @return self
1033 public function setDefaultCommand($commandName, $isSingleCommand = false)
1035 $this->defaultCommand = $commandName;
1037 if ($isSingleCommand) {
1038 // Ensure the command exist
1039 $this->find($commandName);
1041 $this->singleCommand = true;
1044 return $this;
1047 private function splitStringByWidth($string, $width)
1049 // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
1050 // additionally, array_slice() is not enough as some character has doubled width.
1051 // we need a function to split string not by character count but by string width
1052 if (false === $encoding = mb_detect_encoding($string, null, true)) {
1053 return str_split($string, $width);
1056 $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
1057 $lines = array();
1058 $line = '';
1059 foreach (preg_split('//u', $utf8String) as $char) {
1060 // test if $char could be appended to current line
1061 if (mb_strwidth($line.$char, 'utf8') <= $width) {
1062 $line .= $char;
1063 continue;
1065 // if not, push current line to array and make new line
1066 $lines[] = str_pad($line, $width);
1067 $line = $char;
1069 if ('' !== $line) {
1070 $lines[] = count($lines) ? str_pad($line, $width) : $line;
1073 mb_convert_variables($encoding, 'utf8', $lines);
1075 return $lines;
1079 * Returns all namespaces of the command name.
1081 * @param string $name The full name of the command
1083 * @return string[] The namespaces of the command
1085 private function extractAllNamespaces($name)
1087 // -1 as third argument is needed to skip the command short name when exploding
1088 $parts = explode(':', $name, -1);
1089 $namespaces = array();
1091 foreach ($parts as $part) {
1092 if (count($namespaces)) {
1093 $namespaces[] = end($namespaces).':'.$part;
1094 } else {
1095 $namespaces[] = $part;
1099 return $namespaces;