Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Symfony\Component\Console; Chris@0: Chris@0: use Symfony\Component\Console\Exception\ExceptionInterface; Chris@0: use Symfony\Component\Console\Formatter\OutputFormatter; Chris@0: use Symfony\Component\Console\Helper\DebugFormatterHelper; Chris@0: use Symfony\Component\Console\Helper\ProcessHelper; Chris@0: use Symfony\Component\Console\Helper\QuestionHelper; Chris@0: use Symfony\Component\Console\Input\InputInterface; Chris@0: use Symfony\Component\Console\Input\StreamableInputInterface; Chris@0: use Symfony\Component\Console\Input\ArgvInput; Chris@0: use Symfony\Component\Console\Input\ArrayInput; Chris@0: use Symfony\Component\Console\Input\InputDefinition; Chris@0: use Symfony\Component\Console\Input\InputOption; Chris@0: use Symfony\Component\Console\Input\InputArgument; Chris@0: use Symfony\Component\Console\Input\InputAwareInterface; Chris@0: use Symfony\Component\Console\Output\OutputInterface; Chris@0: use Symfony\Component\Console\Output\ConsoleOutput; Chris@0: use Symfony\Component\Console\Output\ConsoleOutputInterface; Chris@0: use Symfony\Component\Console\Command\Command; Chris@0: use Symfony\Component\Console\Command\HelpCommand; Chris@0: use Symfony\Component\Console\Command\ListCommand; Chris@0: use Symfony\Component\Console\Helper\HelperSet; Chris@0: use Symfony\Component\Console\Helper\FormatterHelper; Chris@0: use Symfony\Component\Console\Event\ConsoleCommandEvent; Chris@0: use Symfony\Component\Console\Event\ConsoleExceptionEvent; Chris@0: use Symfony\Component\Console\Event\ConsoleTerminateEvent; Chris@0: use Symfony\Component\Console\Exception\CommandNotFoundException; Chris@0: use Symfony\Component\Console\Exception\LogicException; Chris@0: use Symfony\Component\Debug\Exception\FatalThrowableError; Chris@0: use Symfony\Component\EventDispatcher\EventDispatcherInterface; Chris@0: Chris@0: /** Chris@0: * An Application is the container for a collection of commands. Chris@0: * Chris@0: * It is the main entry point of a Console application. Chris@0: * Chris@0: * This class is optimized for a standard CLI environment. Chris@0: * Chris@0: * Usage: Chris@0: * Chris@0: * $app = new Application('myapp', '1.0 (stable)'); Chris@0: * $app->add(new SimpleCommand()); Chris@0: * $app->run(); Chris@0: * Chris@0: * @author Fabien Potencier Chris@0: */ Chris@0: class Application Chris@0: { Chris@0: private $commands = array(); Chris@0: private $wantHelps = false; Chris@0: private $runningCommand; Chris@0: private $name; Chris@0: private $version; Chris@0: private $catchExceptions = true; Chris@0: private $autoExit = true; Chris@0: private $definition; Chris@0: private $helperSet; Chris@0: private $dispatcher; Chris@0: private $terminal; Chris@0: private $defaultCommand; Chris@0: private $singleCommand; Chris@0: Chris@0: /** Chris@0: * @param string $name The name of the application Chris@0: * @param string $version The version of the application Chris@0: */ Chris@0: public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN') Chris@0: { Chris@0: $this->name = $name; Chris@0: $this->version = $version; Chris@0: $this->terminal = new Terminal(); Chris@0: $this->defaultCommand = 'list'; Chris@0: $this->helperSet = $this->getDefaultHelperSet(); Chris@0: $this->definition = $this->getDefaultInputDefinition(); Chris@0: Chris@0: foreach ($this->getDefaultCommands() as $command) { Chris@0: $this->add($command); Chris@0: } Chris@0: } Chris@0: Chris@0: public function setDispatcher(EventDispatcherInterface $dispatcher) Chris@0: { Chris@0: $this->dispatcher = $dispatcher; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Runs the current application. Chris@0: * Chris@0: * @param InputInterface $input An Input instance Chris@0: * @param OutputInterface $output An Output instance Chris@0: * Chris@0: * @return int 0 if everything went fine, or an error code Chris@0: * Chris@0: * @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}. Chris@0: */ Chris@0: public function run(InputInterface $input = null, OutputInterface $output = null) Chris@0: { Chris@0: putenv('LINES='.$this->terminal->getHeight()); Chris@0: putenv('COLUMNS='.$this->terminal->getWidth()); Chris@0: Chris@0: if (null === $input) { Chris@0: $input = new ArgvInput(); Chris@0: } Chris@0: Chris@0: if (null === $output) { Chris@0: $output = new ConsoleOutput(); Chris@0: } Chris@0: Chris@0: $this->configureIO($input, $output); Chris@0: Chris@0: try { Chris@0: $e = null; Chris@0: $exitCode = $this->doRun($input, $output); Chris@0: } catch (\Exception $x) { Chris@0: $e = $x; Chris@0: } catch (\Throwable $x) { Chris@0: $e = new FatalThrowableError($x); Chris@0: } Chris@0: Chris@0: if (null !== $e) { Chris@0: if (!$this->catchExceptions) { Chris@0: throw $x; Chris@0: } Chris@0: Chris@0: if ($output instanceof ConsoleOutputInterface) { Chris@0: $this->renderException($e, $output->getErrorOutput()); Chris@0: } else { Chris@0: $this->renderException($e, $output); Chris@0: } Chris@0: Chris@0: $exitCode = $e->getCode(); Chris@0: if (is_numeric($exitCode)) { Chris@0: $exitCode = (int) $exitCode; Chris@0: if (0 === $exitCode) { Chris@0: $exitCode = 1; Chris@0: } Chris@0: } else { Chris@0: $exitCode = 1; Chris@0: } Chris@0: } Chris@0: Chris@0: if ($this->autoExit) { Chris@0: if ($exitCode > 255) { Chris@0: $exitCode = 255; Chris@0: } Chris@0: Chris@0: exit($exitCode); Chris@0: } Chris@0: Chris@0: return $exitCode; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Runs the current application. Chris@0: * Chris@0: * @param InputInterface $input An Input instance Chris@0: * @param OutputInterface $output An Output instance Chris@0: * Chris@0: * @return int 0 if everything went fine, or an error code Chris@0: */ Chris@0: public function doRun(InputInterface $input, OutputInterface $output) Chris@0: { Chris@0: if (true === $input->hasParameterOption(array('--version', '-V'), true)) { Chris@0: $output->writeln($this->getLongVersion()); Chris@0: Chris@0: return 0; Chris@0: } Chris@0: Chris@0: $name = $this->getCommandName($input); Chris@0: if (true === $input->hasParameterOption(array('--help', '-h'), true)) { Chris@0: if (!$name) { Chris@0: $name = 'help'; Chris@0: $input = new ArrayInput(array('command_name' => $this->defaultCommand)); Chris@0: } else { Chris@0: $this->wantHelps = true; Chris@0: } Chris@0: } Chris@0: Chris@0: if (!$name) { Chris@0: $name = $this->defaultCommand; Chris@0: $input = new ArrayInput(array('command' => $this->defaultCommand)); Chris@0: } Chris@0: Chris@0: $this->runningCommand = null; Chris@0: // the command name MUST be the first element of the input Chris@0: $command = $this->find($name); Chris@0: Chris@0: $this->runningCommand = $command; Chris@0: $exitCode = $this->doRunCommand($command, $input, $output); Chris@0: $this->runningCommand = null; Chris@0: Chris@0: return $exitCode; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Set a helper set to be used with the command. Chris@0: * Chris@0: * @param HelperSet $helperSet The helper set Chris@0: */ Chris@0: public function setHelperSet(HelperSet $helperSet) Chris@0: { Chris@0: $this->helperSet = $helperSet; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Get the helper set associated with the command. Chris@0: * Chris@0: * @return HelperSet The HelperSet instance associated with this command Chris@0: */ Chris@0: public function getHelperSet() Chris@0: { Chris@0: return $this->helperSet; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Set an input definition to be used with this application. Chris@0: * Chris@0: * @param InputDefinition $definition The input definition Chris@0: */ Chris@0: public function setDefinition(InputDefinition $definition) Chris@0: { Chris@0: $this->definition = $definition; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the InputDefinition related to this Application. Chris@0: * Chris@0: * @return InputDefinition The InputDefinition instance Chris@0: */ Chris@0: public function getDefinition() Chris@0: { Chris@0: if ($this->singleCommand) { Chris@0: $inputDefinition = $this->definition; Chris@0: $inputDefinition->setArguments(); Chris@0: Chris@0: return $inputDefinition; Chris@0: } Chris@0: Chris@0: return $this->definition; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the help message. Chris@0: * Chris@0: * @return string A help message Chris@0: */ Chris@0: public function getHelp() Chris@0: { Chris@0: return $this->getLongVersion(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets whether to catch exceptions or not during commands execution. Chris@0: * Chris@0: * @return bool Whether to catch exceptions or not during commands execution Chris@0: */ Chris@0: public function areExceptionsCaught() Chris@0: { Chris@0: return $this->catchExceptions; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets whether to catch exceptions or not during commands execution. Chris@0: * Chris@0: * @param bool $boolean Whether to catch exceptions or not during commands execution Chris@0: */ Chris@0: public function setCatchExceptions($boolean) Chris@0: { Chris@0: $this->catchExceptions = (bool) $boolean; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets whether to automatically exit after a command execution or not. Chris@0: * Chris@0: * @return bool Whether to automatically exit after a command execution or not Chris@0: */ Chris@0: public function isAutoExitEnabled() Chris@0: { Chris@0: return $this->autoExit; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets whether to automatically exit after a command execution or not. Chris@0: * Chris@0: * @param bool $boolean Whether to automatically exit after a command execution or not Chris@0: */ Chris@0: public function setAutoExit($boolean) Chris@0: { Chris@0: $this->autoExit = (bool) $boolean; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the name of the application. Chris@0: * Chris@0: * @return string The application name Chris@0: */ Chris@0: public function getName() Chris@0: { Chris@0: return $this->name; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the application name. Chris@0: * Chris@0: * @param string $name The application name Chris@0: */ Chris@0: public function setName($name) Chris@0: { Chris@0: $this->name = $name; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the application version. Chris@0: * Chris@0: * @return string The application version Chris@0: */ Chris@0: public function getVersion() Chris@0: { Chris@0: return $this->version; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the application version. Chris@0: * Chris@0: * @param string $version The application version Chris@0: */ Chris@0: public function setVersion($version) Chris@0: { Chris@0: $this->version = $version; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the long version of the application. Chris@0: * Chris@0: * @return string The long application version Chris@0: */ Chris@0: public function getLongVersion() Chris@0: { Chris@0: if ('UNKNOWN' !== $this->getName()) { Chris@0: if ('UNKNOWN' !== $this->getVersion()) { Chris@0: return sprintf('%s %s', $this->getName(), $this->getVersion()); Chris@0: } Chris@0: Chris@0: return $this->getName(); Chris@0: } Chris@0: Chris@0: return 'Console Tool'; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Registers a new command. Chris@0: * Chris@0: * @param string $name The command name Chris@0: * Chris@0: * @return Command The newly created command Chris@0: */ Chris@0: public function register($name) Chris@0: { Chris@0: return $this->add(new Command($name)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds an array of command objects. Chris@0: * Chris@0: * If a Command is not enabled it will not be added. Chris@0: * Chris@0: * @param Command[] $commands An array of commands Chris@0: */ Chris@0: public function addCommands(array $commands) Chris@0: { Chris@0: foreach ($commands as $command) { Chris@0: $this->add($command); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Adds a command object. Chris@0: * Chris@0: * If a command with the same name already exists, it will be overridden. Chris@0: * If the command is not enabled it will not be added. Chris@0: * Chris@0: * @param Command $command A Command object Chris@0: * Chris@0: * @return Command|null The registered command if enabled or null Chris@0: */ Chris@0: public function add(Command $command) Chris@0: { Chris@0: $command->setApplication($this); Chris@0: Chris@0: if (!$command->isEnabled()) { Chris@0: $command->setApplication(null); Chris@0: Chris@0: return; Chris@0: } Chris@0: Chris@0: if (null === $command->getDefinition()) { Chris@0: throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', get_class($command))); Chris@0: } Chris@0: Chris@0: $this->commands[$command->getName()] = $command; Chris@0: Chris@0: foreach ($command->getAliases() as $alias) { Chris@0: $this->commands[$alias] = $command; Chris@0: } Chris@0: Chris@0: return $command; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns a registered command by name or alias. Chris@0: * Chris@0: * @param string $name The command name or alias Chris@0: * Chris@0: * @return Command A Command object Chris@0: * Chris@0: * @throws CommandNotFoundException When given command name does not exist Chris@0: */ Chris@0: public function get($name) Chris@0: { Chris@0: if (!isset($this->commands[$name])) { Chris@0: throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name)); Chris@0: } Chris@0: Chris@0: $command = $this->commands[$name]; Chris@0: Chris@0: if ($this->wantHelps) { Chris@0: $this->wantHelps = false; Chris@0: Chris@0: $helpCommand = $this->get('help'); Chris@0: $helpCommand->setCommand($command); Chris@0: Chris@0: return $helpCommand; Chris@0: } Chris@0: Chris@0: return $command; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns true if the command exists, false otherwise. Chris@0: * Chris@0: * @param string $name The command name or alias Chris@0: * Chris@0: * @return bool true if the command exists, false otherwise Chris@0: */ Chris@0: public function has($name) Chris@0: { Chris@0: return isset($this->commands[$name]); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns an array of all unique namespaces used by currently registered commands. Chris@0: * Chris@0: * It does not return the global namespace which always exists. Chris@0: * Chris@0: * @return string[] An array of namespaces Chris@0: */ Chris@0: public function getNamespaces() Chris@0: { Chris@0: $namespaces = array(); Chris@0: foreach ($this->all() as $command) { Chris@0: $namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName())); Chris@0: Chris@0: foreach ($command->getAliases() as $alias) { Chris@0: $namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias)); Chris@0: } Chris@0: } Chris@0: Chris@0: return array_values(array_unique(array_filter($namespaces))); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Finds a registered namespace by a name or an abbreviation. Chris@0: * Chris@0: * @param string $namespace A namespace or abbreviation to search for Chris@0: * Chris@0: * @return string A registered namespace Chris@0: * Chris@0: * @throws CommandNotFoundException When namespace is incorrect or ambiguous Chris@0: */ Chris@0: public function findNamespace($namespace) Chris@0: { Chris@0: $allNamespaces = $this->getNamespaces(); Chris@0: $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $namespace); Chris@0: $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces); Chris@0: Chris@0: if (empty($namespaces)) { Chris@0: $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace); Chris@0: Chris@0: if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) { Chris@0: if (1 == count($alternatives)) { Chris@0: $message .= "\n\nDid you mean this?\n "; Chris@0: } else { Chris@0: $message .= "\n\nDid you mean one of these?\n "; Chris@0: } Chris@0: Chris@0: $message .= implode("\n ", $alternatives); Chris@0: } Chris@0: Chris@0: throw new CommandNotFoundException($message, $alternatives); Chris@0: } Chris@0: Chris@0: $exact = in_array($namespace, $namespaces, true); Chris@0: if (count($namespaces) > 1 && !$exact) { Chris@0: throw new CommandNotFoundException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))), array_values($namespaces)); Chris@0: } Chris@0: Chris@0: return $exact ? $namespace : reset($namespaces); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Finds a command by name or alias. Chris@0: * Chris@0: * Contrary to get, this command tries to find the best Chris@0: * match if you give it an abbreviation of a name or alias. Chris@0: * Chris@0: * @param string $name A command name or a command alias Chris@0: * Chris@0: * @return Command A Command instance Chris@0: * Chris@0: * @throws CommandNotFoundException When command name is incorrect or ambiguous Chris@0: */ Chris@0: public function find($name) Chris@0: { Chris@0: $allCommands = array_keys($this->commands); Chris@0: $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name); Chris@0: $commands = preg_grep('{^'.$expr.'}', $allCommands); Chris@0: Chris@0: if (empty($commands) || count(preg_grep('{^'.$expr.'$}', $commands)) < 1) { Chris@0: if (false !== $pos = strrpos($name, ':')) { Chris@0: // check if a namespace exists and contains commands Chris@0: $this->findNamespace(substr($name, 0, $pos)); Chris@0: } Chris@0: Chris@0: $message = sprintf('Command "%s" is not defined.', $name); Chris@0: Chris@0: if ($alternatives = $this->findAlternatives($name, $allCommands)) { Chris@0: if (1 == count($alternatives)) { Chris@0: $message .= "\n\nDid you mean this?\n "; Chris@0: } else { Chris@0: $message .= "\n\nDid you mean one of these?\n "; Chris@0: } Chris@0: $message .= implode("\n ", $alternatives); Chris@0: } Chris@0: Chris@0: throw new CommandNotFoundException($message, $alternatives); Chris@0: } Chris@0: Chris@0: // filter out aliases for commands which are already on the list Chris@0: if (count($commands) > 1) { Chris@0: $commandList = $this->commands; Chris@0: $commands = array_filter($commands, function ($nameOrAlias) use ($commandList, $commands) { Chris@0: $commandName = $commandList[$nameOrAlias]->getName(); Chris@0: Chris@0: return $commandName === $nameOrAlias || !in_array($commandName, $commands); Chris@0: }); Chris@0: } Chris@0: Chris@0: $exact = in_array($name, $commands, true); Chris@0: if (count($commands) > 1 && !$exact) { Chris@0: $suggestions = $this->getAbbreviationSuggestions(array_values($commands)); Chris@0: Chris@0: throw new CommandNotFoundException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions), array_values($commands)); Chris@0: } Chris@0: Chris@0: return $this->get($exact ? $name : reset($commands)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the commands (registered in the given namespace if provided). Chris@0: * Chris@0: * The array keys are the full names and the values the command instances. Chris@0: * Chris@0: * @param string $namespace A namespace name Chris@0: * Chris@0: * @return Command[] An array of Command instances Chris@0: */ Chris@0: public function all($namespace = null) Chris@0: { Chris@0: if (null === $namespace) { Chris@0: return $this->commands; Chris@0: } Chris@0: Chris@0: $commands = array(); Chris@0: foreach ($this->commands as $name => $command) { Chris@0: if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) { Chris@0: $commands[$name] = $command; Chris@0: } Chris@0: } Chris@0: Chris@0: return $commands; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns an array of possible abbreviations given a set of names. Chris@0: * Chris@0: * @param array $names An array of names Chris@0: * Chris@0: * @return array An array of abbreviations Chris@0: */ Chris@0: public static function getAbbreviations($names) Chris@0: { Chris@0: $abbrevs = array(); Chris@0: foreach ($names as $name) { Chris@0: for ($len = strlen($name); $len > 0; --$len) { Chris@0: $abbrev = substr($name, 0, $len); Chris@0: $abbrevs[$abbrev][] = $name; Chris@0: } Chris@0: } Chris@0: Chris@0: return $abbrevs; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Renders a caught exception. Chris@0: * Chris@0: * @param \Exception $e An exception instance Chris@0: * @param OutputInterface $output An OutputInterface instance Chris@0: */ Chris@0: public function renderException(\Exception $e, OutputInterface $output) Chris@0: { Chris@0: $output->writeln('', OutputInterface::VERBOSITY_QUIET); Chris@0: Chris@0: do { Chris@0: $title = sprintf( Chris@0: ' [%s%s] ', Chris@0: get_class($e), Chris@0: $output->isVerbose() && 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '' Chris@0: ); Chris@0: Chris@0: $len = $this->stringWidth($title); Chris@0: Chris@0: $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX; Chris@0: // 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 Chris@0: if (defined('HHVM_VERSION') && $width > 1 << 31) { Chris@0: $width = 1 << 31; Chris@0: } Chris@0: $lines = array(); Chris@0: foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) { Chris@0: foreach ($this->splitStringByWidth($line, $width - 4) as $line) { Chris@0: // pre-format lines to get the right string length Chris@0: $lineLength = $this->stringWidth($line) + 4; Chris@0: $lines[] = array($line, $lineLength); Chris@0: Chris@0: $len = max($lineLength, $len); Chris@0: } Chris@0: } Chris@0: Chris@0: $messages = array(); Chris@0: $messages[] = $emptyLine = sprintf('%s', str_repeat(' ', $len)); Chris@0: $messages[] = sprintf('%s%s', $title, str_repeat(' ', max(0, $len - $this->stringWidth($title)))); Chris@0: foreach ($lines as $line) { Chris@0: $messages[] = sprintf(' %s %s', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1])); Chris@0: } Chris@0: $messages[] = $emptyLine; Chris@0: $messages[] = ''; Chris@0: Chris@0: $output->writeln($messages, OutputInterface::VERBOSITY_QUIET); Chris@0: Chris@0: if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { Chris@0: $output->writeln('Exception trace:', OutputInterface::VERBOSITY_QUIET); Chris@0: Chris@0: // exception related properties Chris@0: $trace = $e->getTrace(); Chris@0: array_unshift($trace, array( Chris@0: 'function' => '', Chris@0: 'file' => $e->getFile() !== null ? $e->getFile() : 'n/a', Chris@0: 'line' => $e->getLine() !== null ? $e->getLine() : 'n/a', Chris@0: 'args' => array(), Chris@0: )); Chris@0: Chris@0: for ($i = 0, $count = count($trace); $i < $count; ++$i) { Chris@0: $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : ''; Chris@0: $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : ''; Chris@0: $function = $trace[$i]['function']; Chris@0: $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a'; Chris@0: $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a'; Chris@0: Chris@0: $output->writeln(sprintf(' %s%s%s() at %s:%s', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET); Chris@0: } Chris@0: Chris@0: $output->writeln('', OutputInterface::VERBOSITY_QUIET); Chris@0: } Chris@0: } while ($e = $e->getPrevious()); Chris@0: Chris@0: if (null !== $this->runningCommand) { Chris@0: $output->writeln(sprintf('%s', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET); Chris@0: $output->writeln('', OutputInterface::VERBOSITY_QUIET); Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Tries to figure out the terminal width in which this application runs. Chris@0: * Chris@0: * @return int|null Chris@0: * Chris@0: * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead. Chris@0: */ Chris@0: protected function getTerminalWidth() Chris@0: { Chris@0: @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); Chris@0: Chris@0: return $this->terminal->getWidth(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Tries to figure out the terminal height in which this application runs. Chris@0: * Chris@0: * @return int|null Chris@0: * Chris@0: * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead. Chris@0: */ Chris@0: protected function getTerminalHeight() Chris@0: { Chris@0: @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); Chris@0: Chris@0: return $this->terminal->getHeight(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Tries to figure out the terminal dimensions based on the current environment. Chris@0: * Chris@0: * @return array Array containing width and height Chris@0: * Chris@0: * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead. Chris@0: */ Chris@0: public function getTerminalDimensions() Chris@0: { Chris@0: @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); Chris@0: Chris@0: return array($this->terminal->getWidth(), $this->terminal->getHeight()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets terminal dimensions. Chris@0: * Chris@0: * Can be useful to force terminal dimensions for functional tests. Chris@0: * Chris@0: * @param int $width The width Chris@0: * @param int $height The height Chris@0: * Chris@0: * @return $this Chris@0: * Chris@0: * @deprecated since version 3.2, to be removed in 4.0. Set the COLUMNS and LINES env vars instead. Chris@0: */ Chris@0: public function setTerminalDimensions($width, $height) Chris@0: { Chris@0: @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); Chris@0: Chris@0: putenv('COLUMNS='.$width); Chris@0: putenv('LINES='.$height); Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Configures the input and output instances based on the user arguments and options. Chris@0: * Chris@0: * @param InputInterface $input An InputInterface instance Chris@0: * @param OutputInterface $output An OutputInterface instance Chris@0: */ Chris@0: protected function configureIO(InputInterface $input, OutputInterface $output) Chris@0: { Chris@0: if (true === $input->hasParameterOption(array('--ansi'), true)) { Chris@0: $output->setDecorated(true); Chris@0: } elseif (true === $input->hasParameterOption(array('--no-ansi'), true)) { Chris@0: $output->setDecorated(false); Chris@0: } Chris@0: Chris@0: if (true === $input->hasParameterOption(array('--no-interaction', '-n'), true)) { Chris@0: $input->setInteractive(false); Chris@0: } elseif (function_exists('posix_isatty')) { Chris@0: $inputStream = null; Chris@0: Chris@0: if ($input instanceof StreamableInputInterface) { Chris@0: $inputStream = $input->getStream(); Chris@0: } Chris@0: Chris@0: // This check ensures that calling QuestionHelper::setInputStream() works Chris@0: // To be removed in 4.0 (in the same time as QuestionHelper::setInputStream) Chris@0: if (!$inputStream && $this->getHelperSet()->has('question')) { Chris@0: $inputStream = $this->getHelperSet()->get('question')->getInputStream(false); Chris@0: } Chris@0: Chris@0: if (!@posix_isatty($inputStream) && false === getenv('SHELL_INTERACTIVE')) { Chris@0: $input->setInteractive(false); Chris@0: } Chris@0: } Chris@0: Chris@0: if (true === $input->hasParameterOption(array('--quiet', '-q'), true)) { Chris@0: $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); Chris@0: $input->setInteractive(false); Chris@0: } else { Chris@0: if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || $input->getParameterOption('--verbose', false, true) === 3) { Chris@0: $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); Chris@0: } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || $input->getParameterOption('--verbose', false, true) === 2) { Chris@0: $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); Chris@0: } elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) { Chris@0: $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: /** Chris@0: * Runs the current command. Chris@0: * Chris@0: * If an event dispatcher has been attached to the application, Chris@0: * events are also dispatched during the life-cycle of the command. Chris@0: * Chris@0: * @param Command $command A Command instance Chris@0: * @param InputInterface $input An Input instance Chris@0: * @param OutputInterface $output An Output instance Chris@0: * Chris@0: * @return int 0 if everything went fine, or an error code Chris@0: */ Chris@0: protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output) Chris@0: { Chris@0: foreach ($command->getHelperSet() as $helper) { Chris@0: if ($helper instanceof InputAwareInterface) { Chris@0: $helper->setInput($input); Chris@0: } Chris@0: } Chris@0: Chris@0: if (null === $this->dispatcher) { Chris@0: return $command->run($input, $output); Chris@0: } Chris@0: Chris@0: // bind before the console.command event, so the listeners have access to input options/arguments Chris@0: try { Chris@0: $command->mergeApplicationDefinition(); Chris@0: $input->bind($command->getDefinition()); Chris@0: } catch (ExceptionInterface $e) { Chris@0: // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition Chris@0: } Chris@0: Chris@0: $event = new ConsoleCommandEvent($command, $input, $output); Chris@0: $e = null; Chris@0: Chris@0: try { Chris@0: $this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event); Chris@0: Chris@0: if ($event->commandShouldRun()) { Chris@0: $exitCode = $command->run($input, $output); Chris@0: } else { Chris@0: $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED; Chris@0: } Chris@0: } catch (\Exception $e) { Chris@0: } catch (\Throwable $e) { Chris@0: } Chris@0: if (null !== $e) { Chris@0: $x = $e instanceof \Exception ? $e : new FatalThrowableError($e); Chris@0: $event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode()); Chris@0: $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event); Chris@0: Chris@0: if ($x !== $event->getException()) { Chris@0: $e = $event->getException(); Chris@0: } Chris@0: $exitCode = $e->getCode(); Chris@0: } Chris@0: Chris@0: $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode); Chris@0: $this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event); Chris@0: Chris@0: if (null !== $e) { Chris@0: throw $e; Chris@0: } Chris@0: Chris@0: return $event->getExitCode(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the name of the command based on input. Chris@0: * Chris@0: * @param InputInterface $input The input interface Chris@0: * Chris@0: * @return string The command name Chris@0: */ Chris@0: protected function getCommandName(InputInterface $input) Chris@0: { Chris@0: return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument(); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the default input definition. Chris@0: * Chris@0: * @return InputDefinition An InputDefinition instance Chris@0: */ Chris@0: protected function getDefaultInputDefinition() Chris@0: { Chris@0: return new InputDefinition(array( Chris@0: new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'), Chris@0: Chris@0: new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'), Chris@0: new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'), Chris@0: 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'), Chris@0: new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'), Chris@0: new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'), Chris@0: new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'), Chris@0: new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'), Chris@0: )); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the default commands that should always be available. Chris@0: * Chris@0: * @return Command[] An array of default Command instances Chris@0: */ Chris@0: protected function getDefaultCommands() Chris@0: { Chris@0: return array(new HelpCommand(), new ListCommand()); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Gets the default helper set with the helpers that should always be available. Chris@0: * Chris@0: * @return HelperSet A HelperSet instance Chris@0: */ Chris@0: protected function getDefaultHelperSet() Chris@0: { Chris@0: return new HelperSet(array( Chris@0: new FormatterHelper(), Chris@0: new DebugFormatterHelper(), Chris@0: new ProcessHelper(), Chris@0: new QuestionHelper(), Chris@0: )); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns abbreviated suggestions in string format. Chris@0: * Chris@0: * @param array $abbrevs Abbreviated suggestions to convert Chris@0: * Chris@0: * @return string A formatted string of abbreviated suggestions Chris@0: */ Chris@0: private function getAbbreviationSuggestions($abbrevs) Chris@0: { Chris@0: return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : ''); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the namespace part of the command name. Chris@0: * Chris@0: * This method is not part of public API and should not be used directly. Chris@0: * Chris@0: * @param string $name The full name of the command Chris@0: * @param string $limit The maximum number of parts of the namespace Chris@0: * Chris@0: * @return string The namespace of the command Chris@0: */ Chris@0: public function extractNamespace($name, $limit = null) Chris@0: { Chris@0: $parts = explode(':', $name); Chris@0: array_pop($parts); Chris@0: Chris@0: return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit)); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Finds alternative of $name among $collection, Chris@0: * if nothing is found in $collection, try in $abbrevs. Chris@0: * Chris@0: * @param string $name The string Chris@0: * @param array|\Traversable $collection The collection Chris@0: * Chris@0: * @return string[] A sorted array of similar string Chris@0: */ Chris@0: private function findAlternatives($name, $collection) Chris@0: { Chris@0: $threshold = 1e3; Chris@0: $alternatives = array(); Chris@0: Chris@0: $collectionParts = array(); Chris@0: foreach ($collection as $item) { Chris@0: $collectionParts[$item] = explode(':', $item); Chris@0: } Chris@0: Chris@0: foreach (explode(':', $name) as $i => $subname) { Chris@0: foreach ($collectionParts as $collectionName => $parts) { Chris@0: $exists = isset($alternatives[$collectionName]); Chris@0: if (!isset($parts[$i]) && $exists) { Chris@0: $alternatives[$collectionName] += $threshold; Chris@0: continue; Chris@0: } elseif (!isset($parts[$i])) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: $lev = levenshtein($subname, $parts[$i]); Chris@0: if ($lev <= strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) { Chris@0: $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev; Chris@0: } elseif ($exists) { Chris@0: $alternatives[$collectionName] += $threshold; Chris@0: } Chris@0: } Chris@0: } Chris@0: Chris@0: foreach ($collection as $item) { Chris@0: $lev = levenshtein($name, $item); Chris@0: if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) { Chris@0: $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev; Chris@0: } Chris@0: } Chris@0: Chris@0: $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; }); Chris@0: asort($alternatives); Chris@0: Chris@0: return array_keys($alternatives); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Sets the default Command name. Chris@0: * Chris@0: * @param string $commandName The Command name Chris@0: * @param bool $isSingleCommand Set to true if there is only one command in this application Chris@0: * Chris@0: * @return self Chris@0: */ Chris@0: public function setDefaultCommand($commandName, $isSingleCommand = false) Chris@0: { Chris@0: $this->defaultCommand = $commandName; Chris@0: Chris@0: if ($isSingleCommand) { Chris@0: // Ensure the command exist Chris@0: $this->find($commandName); Chris@0: Chris@0: $this->singleCommand = true; Chris@0: } Chris@0: Chris@0: return $this; Chris@0: } Chris@0: Chris@0: private function stringWidth($string) Chris@0: { Chris@0: if (false === $encoding = mb_detect_encoding($string, null, true)) { Chris@0: return strlen($string); Chris@0: } Chris@0: Chris@0: return mb_strwidth($string, $encoding); Chris@0: } Chris@0: Chris@0: private function splitStringByWidth($string, $width) Chris@0: { Chris@0: // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly. Chris@0: // additionally, array_slice() is not enough as some character has doubled width. Chris@0: // we need a function to split string not by character count but by string width Chris@0: if (false === $encoding = mb_detect_encoding($string, null, true)) { Chris@0: return str_split($string, $width); Chris@0: } Chris@0: Chris@0: $utf8String = mb_convert_encoding($string, 'utf8', $encoding); Chris@0: $lines = array(); Chris@0: $line = ''; Chris@0: foreach (preg_split('//u', $utf8String) as $char) { Chris@0: // test if $char could be appended to current line Chris@0: if (mb_strwidth($line.$char, 'utf8') <= $width) { Chris@0: $line .= $char; Chris@0: continue; Chris@0: } Chris@0: // if not, push current line to array and make new line Chris@0: $lines[] = str_pad($line, $width); Chris@0: $line = $char; Chris@0: } Chris@0: if ('' !== $line) { Chris@0: $lines[] = count($lines) ? str_pad($line, $width) : $line; Chris@0: } Chris@0: Chris@0: mb_convert_variables($encoding, 'utf8', $lines); Chris@0: Chris@0: return $lines; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns all namespaces of the command name. Chris@0: * Chris@0: * @param string $name The full name of the command Chris@0: * Chris@0: * @return string[] The namespaces of the command Chris@0: */ Chris@0: private function extractAllNamespaces($name) Chris@0: { Chris@0: // -1 as third argument is needed to skip the command short name when exploding Chris@0: $parts = explode(':', $name, -1); Chris@0: $namespaces = array(); Chris@0: Chris@0: foreach ($parts as $part) { Chris@0: if (count($namespaces)) { Chris@0: $namespaces[] = end($namespaces).':'.$part; Chris@0: } else { Chris@0: $namespaces[] = $part; Chris@0: } Chris@0: } Chris@0: Chris@0: return $namespaces; Chris@0: } Chris@0: }