namespace Symfony\Component\Console;
+use Symfony\Component\Console\Command\Command;
+use Symfony\Component\Console\Command\HelpCommand;
+use Symfony\Component\Console\Command\ListCommand;
+use Symfony\Component\Console\CommandLoader\CommandLoaderInterface;
+use Symfony\Component\Console\Event\ConsoleCommandEvent;
+use Symfony\Component\Console\Event\ConsoleErrorEvent;
+use Symfony\Component\Console\Event\ConsoleExceptionEvent;
+use Symfony\Component\Console\Event\ConsoleTerminateEvent;
+use Symfony\Component\Console\Exception\CommandNotFoundException;
use Symfony\Component\Console\Exception\ExceptionInterface;
+use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Formatter\OutputFormatter;
use Symfony\Component\Console\Helper\DebugFormatterHelper;
+use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Helper\Helper;
+use Symfony\Component\Console\Helper\HelperSet;
use Symfony\Component\Console\Helper\ProcessHelper;
use Symfony\Component\Console\Helper\QuestionHelper;
-use Symfony\Component\Console\Input\InputInterface;
-use Symfony\Component\Console\Input\StreamableInputInterface;
use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Input\ArrayInput;
-use Symfony\Component\Console\Input\InputDefinition;
-use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputAwareInterface;
-use Symfony\Component\Console\Output\OutputInterface;
+use Symfony\Component\Console\Input\InputDefinition;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Input\InputOption;
+use Symfony\Component\Console\Input\StreamableInputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\ConsoleOutputInterface;
-use Symfony\Component\Console\Command\Command;
-use Symfony\Component\Console\Command\HelpCommand;
-use Symfony\Component\Console\Command\ListCommand;
-use Symfony\Component\Console\Helper\HelperSet;
-use Symfony\Component\Console\Helper\FormatterHelper;
-use Symfony\Component\Console\Event\ConsoleCommandEvent;
-use Symfony\Component\Console\Event\ConsoleExceptionEvent;
-use Symfony\Component\Console\Event\ConsoleTerminateEvent;
-use Symfony\Component\Console\Exception\CommandNotFoundException;
-use Symfony\Component\Console\Exception\LogicException;
+use Symfony\Component\Console\Output\OutputInterface;
+use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\Exception\FatalThrowableError;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
private $runningCommand;
private $name;
private $version;
+ private $commandLoader;
private $catchExceptions = true;
private $autoExit = true;
private $definition;
private $terminal;
private $defaultCommand;
private $singleCommand;
+ private $initialized;
/**
* @param string $name The name of the application
$this->version = $version;
$this->terminal = new Terminal();
$this->defaultCommand = 'list';
- $this->helperSet = $this->getDefaultHelperSet();
- $this->definition = $this->getDefaultInputDefinition();
-
- foreach ($this->getDefaultCommands() as $command) {
- $this->add($command);
- }
}
public function setDispatcher(EventDispatcherInterface $dispatcher)
$this->dispatcher = $dispatcher;
}
+ public function setCommandLoader(CommandLoaderInterface $commandLoader)
+ {
+ $this->commandLoader = $commandLoader;
+ }
+
/**
* Runs the current application.
*
- * @param InputInterface $input An Input instance
- * @param OutputInterface $output An Output instance
- *
* @return int 0 if everything went fine, or an error code
*
* @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}.
$output = new ConsoleOutput();
}
- $this->configureIO($input, $output);
-
- try {
- $e = null;
- $exitCode = $this->doRun($input, $output);
- } catch (\Exception $x) {
- $e = $x;
- } catch (\Throwable $x) {
- $e = new FatalThrowableError($x);
- }
-
- if (null !== $e) {
- if (!$this->catchExceptions || !$x instanceof \Exception) {
- throw $x;
+ $renderException = function ($e) use ($output) {
+ if (!$e instanceof \Exception) {
+ $e = class_exists(FatalThrowableError::class) ? new FatalThrowableError($e) : new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
}
-
if ($output instanceof ConsoleOutputInterface) {
$this->renderException($e, $output->getErrorOutput());
} else {
$this->renderException($e, $output);
}
+ };
+ if ($phpHandler = set_exception_handler($renderException)) {
+ restore_exception_handler();
+ if (!\is_array($phpHandler) || !$phpHandler[0] instanceof ErrorHandler) {
+ $debugHandler = true;
+ } elseif ($debugHandler = $phpHandler[0]->setExceptionHandler($renderException)) {
+ $phpHandler[0]->setExceptionHandler($debugHandler);
+ }
+ }
+
+ if (null !== $this->dispatcher && $this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) {
+ @trigger_error(sprintf('The "ConsoleEvents::EXCEPTION" event is deprecated since Symfony 3.3 and will be removed in 4.0. Listen to the "ConsoleEvents::ERROR" event instead.'), E_USER_DEPRECATED);
+ }
+
+ $this->configureIO($input, $output);
+
+ try {
+ $exitCode = $this->doRun($input, $output);
+ } catch (\Exception $e) {
+ if (!$this->catchExceptions) {
+ throw $e;
+ }
+
+ $renderException($e);
$exitCode = $e->getCode();
if (is_numeric($exitCode)) {
} else {
$exitCode = 1;
}
+ } finally {
+ // if the exception handler changed, keep it
+ // otherwise, unregister $renderException
+ if (!$phpHandler) {
+ if (set_exception_handler($renderException) === $renderException) {
+ restore_exception_handler();
+ }
+ restore_exception_handler();
+ } elseif (!$debugHandler) {
+ $finalHandler = $phpHandler[0]->setExceptionHandler(null);
+ if ($finalHandler !== $renderException) {
+ $phpHandler[0]->setExceptionHandler($finalHandler);
+ }
+ }
}
if ($this->autoExit) {
/**
* Runs the current application.
*
- * @param InputInterface $input An Input instance
- * @param OutputInterface $output An Output instance
- *
* @return int 0 if everything went fine, or an error code
*/
public function doRun(InputInterface $input, OutputInterface $output)
if (!$name) {
$name = $this->defaultCommand;
- $this->definition->setArguments(array_merge(
- $this->definition->getArguments(),
+ $definition = $this->getDefinition();
+ $definition->setArguments(array_merge(
+ $definition->getArguments(),
array(
- 'command' => new InputArgument('command', InputArgument::OPTIONAL, $this->definition->getArgument('command')->getDescription(), $name),
+ 'command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name),
)
));
}
- $this->runningCommand = null;
- // the command name MUST be the first element of the input
- $command = $this->find($name);
+ try {
+ $e = $this->runningCommand = null;
+ // the command name MUST be the first element of the input
+ $command = $this->find($name);
+ } catch (\Exception $e) {
+ } catch (\Throwable $e) {
+ }
+ if (null !== $e) {
+ if (null !== $this->dispatcher) {
+ $event = new ConsoleErrorEvent($input, $output, $e);
+ $this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
+ $e = $event->getError();
+
+ if (0 === $event->getExitCode()) {
+ return 0;
+ }
+ }
+
+ throw $e;
+ }
$this->runningCommand = $command;
$exitCode = $this->doRunCommand($command, $input, $output);
return $exitCode;
}
- /**
- * Set a helper set to be used with the command.
- *
- * @param HelperSet $helperSet The helper set
- */
public function setHelperSet(HelperSet $helperSet)
{
$this->helperSet = $helperSet;
*/
public function getHelperSet()
{
+ if (!$this->helperSet) {
+ $this->helperSet = $this->getDefaultHelperSet();
+ }
+
return $this->helperSet;
}
- /**
- * Set an input definition to be used with this application.
- *
- * @param InputDefinition $definition The input definition
- */
public function setDefinition(InputDefinition $definition)
{
$this->definition = $definition;
*/
public function getDefinition()
{
+ if (!$this->definition) {
+ $this->definition = $this->getDefaultInputDefinition();
+ }
+
if ($this->singleCommand) {
$inputDefinition = $this->definition;
$inputDefinition->setArguments();
* If a command with the same name already exists, it will be overridden.
* If the command is not enabled it will not be added.
*
- * @param Command $command A Command object
- *
* @return Command|null The registered command if enabled or null
*/
public function add(Command $command)
{
+ $this->init();
+
$command->setApplication($this);
if (!$command->isEnabled()) {
}
if (null === $command->getDefinition()) {
- throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', get_class($command)));
+ throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', \get_class($command)));
+ }
+
+ if (!$command->getName()) {
+ throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', \get_class($command)));
}
$this->commands[$command->getName()] = $command;
*/
public function get($name)
{
- if (!isset($this->commands[$name])) {
+ $this->init();
+
+ if (!$this->has($name)) {
throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name));
}
*/
public function has($name)
{
- return isset($this->commands[$name]);
+ $this->init();
+
+ return isset($this->commands[$name]) || ($this->commandLoader && $this->commandLoader->has($name) && $this->add($this->commandLoader->get($name)));
}
/**
$message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
- if (1 == count($alternatives)) {
+ if (1 == \count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
} else {
$message .= "\n\nDid you mean one of these?\n ";
throw new CommandNotFoundException($message, $alternatives);
}
- $exact = in_array($namespace, $namespaces, true);
- if (count($namespaces) > 1 && !$exact) {
- throw new CommandNotFoundException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
+ $exact = \in_array($namespace, $namespaces, true);
+ if (\count($namespaces) > 1 && !$exact) {
+ throw new CommandNotFoundException(sprintf("The namespace \"%s\" is ambiguous.\nDid you mean one of these?\n%s", $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces));
}
return $exact ? $namespace : reset($namespaces);
*/
public function find($name)
{
- $allCommands = array_keys($this->commands);
+ $this->init();
+
+ $aliases = array();
+ $allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
$expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
$commands = preg_grep('{^'.$expr.'}', $allCommands);
- if (empty($commands) || count(preg_grep('{^'.$expr.'$}', $commands)) < 1) {
+ if (empty($commands)) {
+ $commands = preg_grep('{^'.$expr.'}i', $allCommands);
+ }
+
+ // if no commands matched or we just matched namespaces
+ if (empty($commands) || \count(preg_grep('{^'.$expr.'$}i', $commands)) < 1) {
if (false !== $pos = strrpos($name, ':')) {
// check if a namespace exists and contains commands
$this->findNamespace(substr($name, 0, $pos));
$message = sprintf('Command "%s" is not defined.', $name);
if ($alternatives = $this->findAlternatives($name, $allCommands)) {
- if (1 == count($alternatives)) {
+ if (1 == \count($alternatives)) {
$message .= "\n\nDid you mean this?\n ";
} else {
$message .= "\n\nDid you mean one of these?\n ";
}
// filter out aliases for commands which are already on the list
- if (count($commands) > 1) {
- $commandList = $this->commands;
- $commands = array_filter($commands, function ($nameOrAlias) use ($commandList, $commands) {
- $commandName = $commandList[$nameOrAlias]->getName();
-
- return $commandName === $nameOrAlias || !in_array($commandName, $commands);
- });
+ if (\count($commands) > 1) {
+ $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands;
+ $commands = array_unique(array_filter($commands, function ($nameOrAlias) use ($commandList, $commands, &$aliases) {
+ $commandName = $commandList[$nameOrAlias] instanceof Command ? $commandList[$nameOrAlias]->getName() : $nameOrAlias;
+ $aliases[$nameOrAlias] = $commandName;
+
+ return $commandName === $nameOrAlias || !\in_array($commandName, $commands);
+ }));
}
- $exact = in_array($name, $commands, true);
- if (count($commands) > 1 && !$exact) {
- $suggestions = $this->getAbbreviationSuggestions(array_values($commands));
+ $exact = \in_array($name, $commands, true) || isset($aliases[$name]);
+ if (\count($commands) > 1 && !$exact) {
+ $usableWidth = $this->terminal->getWidth() - 10;
+ $abbrevs = array_values($commands);
+ $maxLen = 0;
+ foreach ($abbrevs as $abbrev) {
+ $maxLen = max(Helper::strlen($abbrev), $maxLen);
+ }
+ $abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen) {
+ if (!$commandList[$cmd] instanceof Command) {
+ return $cmd;
+ }
+ $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription();
+
+ return Helper::strlen($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev;
+ }, array_values($commands));
+ $suggestions = $this->getAbbreviationSuggestions($abbrevs);
- throw new CommandNotFoundException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions), array_values($commands));
+ throw new CommandNotFoundException(sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s", $name, $suggestions), array_values($commands));
}
return $this->get($exact ? $name : reset($commands));
*/
public function all($namespace = null)
{
+ $this->init();
+
if (null === $namespace) {
- return $this->commands;
+ if (!$this->commandLoader) {
+ return $this->commands;
+ }
+
+ $commands = $this->commands;
+ foreach ($this->commandLoader->getNames() as $name) {
+ if (!isset($commands[$name]) && $this->has($name)) {
+ $commands[$name] = $this->get($name);
+ }
+ }
+
+ return $commands;
}
$commands = array();
}
}
+ if ($this->commandLoader) {
+ foreach ($this->commandLoader->getNames() as $name) {
+ if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) {
+ $commands[$name] = $this->get($name);
+ }
+ }
+ }
+
return $commands;
}
{
$abbrevs = array();
foreach ($names as $name) {
- for ($len = strlen($name); $len > 0; --$len) {
+ for ($len = \strlen($name); $len > 0; --$len) {
$abbrev = substr($name, 0, $len);
$abbrevs[$abbrev][] = $name;
}
/**
* Renders a caught exception.
- *
- * @param \Exception $e An exception instance
- * @param OutputInterface $output An OutputInterface instance
*/
public function renderException(\Exception $e, OutputInterface $output)
{
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
- do {
- $title = sprintf(
- ' [%s%s] ',
- get_class($e),
- $output->isVerbose() && 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : ''
- );
+ $this->doRenderException($e, $output);
+
+ if (null !== $this->runningCommand) {
+ $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
+ $output->writeln('', OutputInterface::VERBOSITY_QUIET);
+ }
+ }
- $len = Helper::strlen($title);
+ protected function doRenderException(\Exception $e, OutputInterface $output)
+ {
+ do {
+ $message = trim($e->getMessage());
+ if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
+ $title = sprintf(' [%s%s] ', \get_class($e), 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
+ $len = Helper::strlen($title);
+ } else {
+ $len = 0;
+ }
$width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX;
// 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
- if (defined('HHVM_VERSION') && $width > 1 << 31) {
+ if (\defined('HHVM_VERSION') && $width > 1 << 31) {
$width = 1 << 31;
}
$lines = array();
- foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
+ foreach ('' !== $message ? preg_split('/\r?\n/', $message) : array() as $line) {
foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
// pre-format lines to get the right string length
$lineLength = Helper::strlen($line) + 4;
}
$messages = array();
+ if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
+ $messages[] = sprintf('<comment>%s</comment>', OutputFormatter::escape(sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a')));
+ }
$messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
- $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
+ if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
+ $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
+ }
foreach ($lines as $line) {
$messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
}
// exception related properties
$trace = $e->getTrace();
- array_unshift($trace, array(
- 'function' => '',
- 'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
- 'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
- 'args' => array(),
- ));
-
- for ($i = 0, $count = count($trace); $i < $count; ++$i) {
+
+ for ($i = 0, $count = \count($trace); $i < $count; ++$i) {
$class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
$type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
$function = $trace[$i]['function'];
$output->writeln('', OutputInterface::VERBOSITY_QUIET);
}
} while ($e = $e->getPrevious());
-
- if (null !== $this->runningCommand) {
- $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
- $output->writeln('', OutputInterface::VERBOSITY_QUIET);
- }
}
/**
*/
protected function getTerminalWidth()
{
- @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);
+ @trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), E_USER_DEPRECATED);
return $this->terminal->getWidth();
}
*/
protected function getTerminalHeight()
{
- @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);
+ @trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), E_USER_DEPRECATED);
return $this->terminal->getHeight();
}
*/
public function getTerminalDimensions()
{
- @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);
+ @trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Create a Terminal instance instead.', __METHOD__), E_USER_DEPRECATED);
return array($this->terminal->getWidth(), $this->terminal->getHeight());
}
*/
public function setTerminalDimensions($width, $height)
{
- @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);
+ @trigger_error(sprintf('The "%s()" method is deprecated as of 3.2 and will be removed in 4.0. Set the COLUMNS and LINES env vars instead.', __METHOD__), E_USER_DEPRECATED);
putenv('COLUMNS='.$width);
putenv('LINES='.$height);
/**
* Configures the input and output instances based on the user arguments and options.
- *
- * @param InputInterface $input An InputInterface instance
- * @param OutputInterface $output An OutputInterface instance
*/
protected function configureIO(InputInterface $input, OutputInterface $output)
{
if (true === $input->hasParameterOption(array('--no-interaction', '-n'), true)) {
$input->setInteractive(false);
- } elseif (function_exists('posix_isatty')) {
+ } elseif (\function_exists('posix_isatty')) {
$inputStream = null;
if ($input instanceof StreamableInputInterface) {
}
}
+ switch ($shellVerbosity = (int) getenv('SHELL_VERBOSITY')) {
+ case -1: $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); break;
+ case 1: $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); break;
+ case 2: $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); break;
+ case 3: $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); break;
+ default: $shellVerbosity = 0; break;
+ }
+
if (true === $input->hasParameterOption(array('--quiet', '-q'), true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
- $input->setInteractive(false);
+ $shellVerbosity = -1;
} else {
- if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || $input->getParameterOption('--verbose', false, true) === 3) {
+ if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
- } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || $input->getParameterOption('--verbose', false, true) === 2) {
+ $shellVerbosity = 3;
+ } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
+ $shellVerbosity = 2;
} elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) {
$output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
+ $shellVerbosity = 1;
}
}
+
+ if (-1 === $shellVerbosity) {
+ $input->setInteractive(false);
+ }
+
+ putenv('SHELL_VERBOSITY='.$shellVerbosity);
+ $_ENV['SHELL_VERBOSITY'] = $shellVerbosity;
+ $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity;
}
/**
* If an event dispatcher has been attached to the application,
* events are also dispatched during the life-cycle of the command.
*
- * @param Command $command A Command instance
- * @param InputInterface $input An Input instance
- * @param OutputInterface $output An Output instance
- *
* @return int 0 if everything went fine, or an error code
*/
protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
} catch (\Throwable $e) {
}
if (null !== $e) {
- $x = $e instanceof \Exception ? $e : new FatalThrowableError($e);
- $event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode());
- $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
+ if ($this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) {
+ $x = $e instanceof \Exception ? $e : new FatalThrowableError($e);
+ $event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode());
+ $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
- if ($x !== $event->getException()) {
- $e = $event->getException();
+ if ($x !== $event->getException()) {
+ $e = $event->getException();
+ }
+ }
+ $event = new ConsoleErrorEvent($input, $output, $e, $command);
+ $this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
+ $e = $event->getError();
+
+ if (0 === $exitCode = $event->getExitCode()) {
+ $e = null;
}
- $exitCode = $e->getCode();
}
$event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
/**
* Gets the name of the command based on input.
*
- * @param InputInterface $input The input interface
- *
* @return string The command name
*/
protected function getCommandName(InputInterface $input)
*/
private function getAbbreviationSuggestions($abbrevs)
{
- return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
+ return ' '.implode("\n ", $abbrevs);
}
/**
$parts = explode(':', $name);
array_pop($parts);
- return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
+ return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit));
}
/**
* Finds alternative of $name among $collection,
* if nothing is found in $collection, try in $abbrevs.
*
- * @param string $name The string
- * @param array|\Traversable $collection The collection
+ * @param string $name The string
+ * @param iterable $collection The collection
*
* @return string[] A sorted array of similar string
*/
}
$lev = levenshtein($subname, $parts[$i]);
- if ($lev <= strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
+ if ($lev <= \strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
$alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
} elseif ($exists) {
$alternatives[$collectionName] += $threshold;
foreach ($collection as $item) {
$lev = levenshtein($name, $item);
- if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
+ if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
$alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
}
}
$alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
- asort($alternatives);
+ ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE);
return array_keys($alternatives);
}
$lines[] = str_pad($line, $width);
$line = $char;
}
- if ('' !== $line) {
- $lines[] = count($lines) ? str_pad($line, $width) : $line;
- }
+
+ $lines[] = \count($lines) ? str_pad($line, $width) : $line;
mb_convert_variables($encoding, 'utf8', $lines);
$namespaces = array();
foreach ($parts as $part) {
- if (count($namespaces)) {
+ if (\count($namespaces)) {
$namespaces[] = end($namespaces).':'.$part;
} else {
$namespaces[] = $part;
return $namespaces;
}
+
+ private function init()
+ {
+ if ($this->initialized) {
+ return;
+ }
+ $this->initialized = true;
+
+ foreach ($this->getDefaultCommands() as $command) {
+ $this->add($command);
+ }
+ }
}