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\Command\Command; Chris@0: use Symfony\Component\Console\Command\HelpCommand; Chris@0: use Symfony\Component\Console\Command\ListCommand; Chris@17: use Symfony\Component\Console\CommandLoader\CommandLoaderInterface; Chris@0: use Symfony\Component\Console\Event\ConsoleCommandEvent; Chris@14: use Symfony\Component\Console\Event\ConsoleErrorEvent; 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@17: use Symfony\Component\Console\Exception\ExceptionInterface; Chris@0: use Symfony\Component\Console\Exception\LogicException; Chris@17: use Symfony\Component\Console\Formatter\OutputFormatter; Chris@17: use Symfony\Component\Console\Helper\DebugFormatterHelper; Chris@17: use Symfony\Component\Console\Helper\FormatterHelper; Chris@17: use Symfony\Component\Console\Helper\Helper; Chris@17: use Symfony\Component\Console\Helper\HelperSet; Chris@17: use Symfony\Component\Console\Helper\ProcessHelper; Chris@17: use Symfony\Component\Console\Helper\QuestionHelper; Chris@17: use Symfony\Component\Console\Input\ArgvInput; Chris@17: use Symfony\Component\Console\Input\ArrayInput; Chris@17: use Symfony\Component\Console\Input\InputArgument; Chris@17: use Symfony\Component\Console\Input\InputAwareInterface; Chris@17: use Symfony\Component\Console\Input\InputDefinition; Chris@17: use Symfony\Component\Console\Input\InputInterface; Chris@17: use Symfony\Component\Console\Input\InputOption; Chris@17: use Symfony\Component\Console\Input\StreamableInputInterface; Chris@17: use Symfony\Component\Console\Output\ConsoleOutput; Chris@17: use Symfony\Component\Console\Output\ConsoleOutputInterface; Chris@17: use Symfony\Component\Console\Output\OutputInterface; Chris@14: use Symfony\Component\Debug\ErrorHandler; 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@17: private $commands = []; Chris@0: private $wantHelps = false; Chris@0: private $runningCommand; Chris@0: private $name; Chris@0: private $version; Chris@14: private $commandLoader; 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@17: private $singleCommand = false; Chris@14: private $initialized; 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: } Chris@0: Chris@0: public function setDispatcher(EventDispatcherInterface $dispatcher) Chris@0: { Chris@0: $this->dispatcher = $dispatcher; Chris@0: } Chris@0: Chris@14: public function setCommandLoader(CommandLoaderInterface $commandLoader) Chris@14: { Chris@14: $this->commandLoader = $commandLoader; Chris@14: } Chris@14: Chris@0: /** Chris@0: * Runs the current application. 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@14: $renderException = function ($e) use ($output) { Chris@14: if (!$e instanceof \Exception) { Chris@14: $e = class_exists(FatalThrowableError::class) ? new FatalThrowableError($e) : new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine()); 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@14: }; Chris@14: if ($phpHandler = set_exception_handler($renderException)) { Chris@14: restore_exception_handler(); Chris@17: if (!\is_array($phpHandler) || !$phpHandler[0] instanceof ErrorHandler) { Chris@14: $debugHandler = true; Chris@14: } elseif ($debugHandler = $phpHandler[0]->setExceptionHandler($renderException)) { Chris@14: $phpHandler[0]->setExceptionHandler($debugHandler); Chris@14: } Chris@14: } Chris@14: Chris@14: if (null !== $this->dispatcher && $this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) { Chris@14: @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); Chris@14: } Chris@14: Chris@14: $this->configureIO($input, $output); Chris@14: Chris@14: try { Chris@14: $exitCode = $this->doRun($input, $output); Chris@14: } catch (\Exception $e) { Chris@14: if (!$this->catchExceptions) { Chris@14: throw $e; Chris@14: } Chris@14: Chris@14: $renderException($e); 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@14: } finally { Chris@14: // if the exception handler changed, keep it Chris@14: // otherwise, unregister $renderException Chris@14: if (!$phpHandler) { Chris@14: if (set_exception_handler($renderException) === $renderException) { Chris@14: restore_exception_handler(); Chris@14: } Chris@14: restore_exception_handler(); Chris@14: } elseif (!$debugHandler) { Chris@14: $finalHandler = $phpHandler[0]->setExceptionHandler(null); Chris@14: if ($finalHandler !== $renderException) { Chris@14: $phpHandler[0]->setExceptionHandler($finalHandler); Chris@14: } Chris@14: } 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: * @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@17: if (true === $input->hasParameterOption(['--version', '-V'], true)) { Chris@0: $output->writeln($this->getLongVersion()); Chris@0: Chris@0: return 0; Chris@0: } Chris@0: Chris@18: try { Chris@18: // Makes ArgvInput::getFirstArgument() able to distinguish an option from an argument. Chris@18: $input->bind($this->getDefinition()); Chris@18: } catch (ExceptionInterface $e) { Chris@18: // Errors must be ignored, full binding/validation happens later when the command is known. Chris@18: } Chris@18: Chris@0: $name = $this->getCommandName($input); Chris@17: if (true === $input->hasParameterOption(['--help', '-h'], true)) { Chris@0: if (!$name) { Chris@0: $name = 'help'; Chris@17: $input = new ArrayInput(['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@14: $definition = $this->getDefinition(); Chris@14: $definition->setArguments(array_merge( Chris@14: $definition->getArguments(), Chris@17: [ Chris@14: 'command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name), Chris@17: ] Chris@12: )); Chris@0: } Chris@0: Chris@14: try { Chris@14: $e = $this->runningCommand = null; Chris@14: // the command name MUST be the first element of the input Chris@14: $command = $this->find($name); Chris@14: } catch (\Exception $e) { Chris@14: } catch (\Throwable $e) { Chris@14: } Chris@14: if (null !== $e) { Chris@14: if (null !== $this->dispatcher) { Chris@14: $event = new ConsoleErrorEvent($input, $output, $e); Chris@14: $this->dispatcher->dispatch(ConsoleEvents::ERROR, $event); Chris@14: $e = $event->getError(); Chris@14: Chris@14: if (0 === $event->getExitCode()) { Chris@14: return 0; Chris@14: } Chris@14: } Chris@14: Chris@14: throw $e; Chris@14: } 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: 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@14: if (!$this->helperSet) { Chris@14: $this->helperSet = $this->getDefaultHelperSet(); Chris@14: } Chris@14: Chris@0: return $this->helperSet; Chris@0: } 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@14: if (!$this->definition) { Chris@14: $this->definition = $this->getDefaultInputDefinition(); Chris@14: } Chris@14: 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: * @return Command|null The registered command if enabled or null Chris@0: */ Chris@0: public function add(Command $command) Chris@0: { Chris@14: $this->init(); Chris@14: 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@17: 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@14: if (!$command->getName()) { Chris@17: throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', \get_class($command))); Chris@14: } Chris@14: 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@14: $this->init(); Chris@14: Chris@14: if (!$this->has($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@14: $this->init(); Chris@14: Chris@14: return isset($this->commands[$name]) || ($this->commandLoader && $this->commandLoader->has($name) && $this->add($this->commandLoader->get($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@17: $namespaces = []; 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@17: 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@17: $exact = \in_array($namespace, $namespaces, true); Chris@17: if (\count($namespaces) > 1 && !$exact) { Chris@14: 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)); 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@14: $this->init(); Chris@14: Chris@17: $aliases = []; Chris@14: $allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : 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@14: if (empty($commands)) { Chris@14: $commands = preg_grep('{^'.$expr.'}i', $allCommands); Chris@14: } Chris@14: Chris@14: // if no commands matched or we just matched namespaces Chris@17: if (empty($commands) || \count(preg_grep('{^'.$expr.'$}i', $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@17: 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@17: if (\count($commands) > 1) { Chris@14: $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands; Chris@14: $commands = array_unique(array_filter($commands, function ($nameOrAlias) use ($commandList, $commands, &$aliases) { Chris@14: $commandName = $commandList[$nameOrAlias] instanceof Command ? $commandList[$nameOrAlias]->getName() : $nameOrAlias; Chris@14: $aliases[$nameOrAlias] = $commandName; Chris@0: Chris@17: return $commandName === $nameOrAlias || !\in_array($commandName, $commands); Chris@14: })); Chris@0: } Chris@0: Chris@17: $exact = \in_array($name, $commands, true) || isset($aliases[$name]); Chris@17: if (\count($commands) > 1 && !$exact) { Chris@14: $usableWidth = $this->terminal->getWidth() - 10; Chris@14: $abbrevs = array_values($commands); Chris@14: $maxLen = 0; Chris@14: foreach ($abbrevs as $abbrev) { Chris@14: $maxLen = max(Helper::strlen($abbrev), $maxLen); Chris@14: } Chris@14: $abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen) { Chris@14: if (!$commandList[$cmd] instanceof Command) { Chris@14: return $cmd; Chris@14: } Chris@14: $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription(); Chris@0: Chris@14: return Helper::strlen($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev; Chris@14: }, array_values($commands)); Chris@14: $suggestions = $this->getAbbreviationSuggestions($abbrevs); Chris@14: Chris@14: throw new CommandNotFoundException(sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%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@14: $this->init(); Chris@14: Chris@0: if (null === $namespace) { Chris@14: if (!$this->commandLoader) { Chris@14: return $this->commands; Chris@14: } Chris@14: Chris@14: $commands = $this->commands; Chris@14: foreach ($this->commandLoader->getNames() as $name) { Chris@14: if (!isset($commands[$name]) && $this->has($name)) { Chris@14: $commands[$name] = $this->get($name); Chris@14: } Chris@14: } Chris@14: Chris@14: return $commands; Chris@0: } Chris@0: Chris@17: $commands = []; 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@14: if ($this->commandLoader) { Chris@14: foreach ($this->commandLoader->getNames() as $name) { Chris@14: if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) { Chris@14: $commands[$name] = $this->get($name); Chris@14: } Chris@14: } Chris@14: } Chris@14: 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@17: $abbrevs = []; Chris@0: foreach ($names as $name) { Chris@17: 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: public function renderException(\Exception $e, OutputInterface $output) Chris@0: { Chris@0: $output->writeln('', OutputInterface::VERBOSITY_QUIET); Chris@0: Chris@14: $this->doRenderException($e, $output); Chris@14: Chris@14: if (null !== $this->runningCommand) { Chris@14: $output->writeln(sprintf('%s', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET); Chris@14: $output->writeln('', OutputInterface::VERBOSITY_QUIET); Chris@14: } Chris@14: } Chris@14: Chris@14: protected function doRenderException(\Exception $e, OutputInterface $output) Chris@14: { Chris@0: do { Chris@14: $message = trim($e->getMessage()); Chris@14: if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { Chris@17: $title = sprintf(' [%s%s] ', \get_class($e), 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : ''); Chris@14: $len = Helper::strlen($title); Chris@14: } else { Chris@14: $len = 0; Chris@14: } 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@17: if (\defined('HHVM_VERSION') && $width > 1 << 31) { Chris@0: $width = 1 << 31; Chris@0: } Chris@17: $lines = []; Chris@17: foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) { Chris@0: foreach ($this->splitStringByWidth($line, $width - 4) as $line) { Chris@0: // pre-format lines to get the right string length Chris@12: $lineLength = Helper::strlen($line) + 4; Chris@17: $lines[] = [$line, $lineLength]; Chris@0: Chris@0: $len = max($lineLength, $len); Chris@0: } Chris@0: } Chris@0: Chris@17: $messages = []; Chris@14: if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { Chris@14: $messages[] = sprintf('%s', OutputFormatter::escape(sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a'))); Chris@14: } Chris@0: $messages[] = $emptyLine = sprintf('%s', str_repeat(' ', $len)); Chris@14: if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { Chris@14: $messages[] = sprintf('%s%s', $title, str_repeat(' ', max(0, $len - Helper::strlen($title)))); Chris@14: } 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: Chris@17: array_unshift($trace, [ Chris@17: 'function' => '', Chris@17: 'file' => $e->getFile() ?: 'n/a', Chris@17: 'line' => $e->getLine() ?: 'n/a', Chris@17: 'args' => [], Chris@17: ]); Chris@17: Chris@17: 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: 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@17: @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); 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@17: @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); 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@17: @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); Chris@0: Chris@17: return [$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@17: @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); 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: protected function configureIO(InputInterface $input, OutputInterface $output) Chris@0: { Chris@17: if (true === $input->hasParameterOption(['--ansi'], true)) { Chris@0: $output->setDecorated(true); Chris@17: } elseif (true === $input->hasParameterOption(['--no-ansi'], true)) { Chris@0: $output->setDecorated(false); Chris@0: } Chris@0: Chris@17: if (true === $input->hasParameterOption(['--no-interaction', '-n'], true)) { Chris@0: $input->setInteractive(false); Chris@17: } 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@14: switch ($shellVerbosity = (int) getenv('SHELL_VERBOSITY')) { Chris@14: case -1: $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); break; Chris@14: case 1: $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); break; Chris@14: case 2: $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); break; Chris@14: case 3: $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); break; Chris@14: default: $shellVerbosity = 0; break; Chris@14: } Chris@14: Chris@17: if (true === $input->hasParameterOption(['--quiet', '-q'], true)) { Chris@0: $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); Chris@14: $shellVerbosity = -1; Chris@0: } else { Chris@14: if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true)) { Chris@0: $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); Chris@14: $shellVerbosity = 3; Chris@14: } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true)) { Chris@0: $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); Chris@14: $shellVerbosity = 2; 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@14: $shellVerbosity = 1; Chris@0: } Chris@0: } Chris@14: Chris@14: if (-1 === $shellVerbosity) { Chris@14: $input->setInteractive(false); Chris@14: } Chris@14: Chris@14: putenv('SHELL_VERBOSITY='.$shellVerbosity); Chris@14: $_ENV['SHELL_VERBOSITY'] = $shellVerbosity; Chris@14: $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity; 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: * @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@14: if ($this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) { Chris@14: $x = $e instanceof \Exception ? $e : new FatalThrowableError($e); Chris@14: $event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode()); Chris@14: $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event); Chris@0: Chris@14: if ($x !== $event->getException()) { Chris@14: $e = $event->getException(); Chris@14: } Chris@0: } Chris@14: $event = new ConsoleErrorEvent($input, $output, $e, $command); Chris@14: $this->dispatcher->dispatch(ConsoleEvents::ERROR, $event); Chris@14: $e = $event->getError(); Chris@14: Chris@14: if (0 === $exitCode = $event->getExitCode()) { Chris@14: $e = null; Chris@14: } 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: * @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@17: return new InputDefinition([ 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@17: ]); 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@17: return [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@17: return new HelperSet([ Chris@0: new FormatterHelper(), Chris@0: new DebugFormatterHelper(), Chris@0: new ProcessHelper(), Chris@0: new QuestionHelper(), Chris@17: ]); 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@14: return ' '.implode("\n ", $abbrevs); 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@17: 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@14: * @param string $name The string Chris@14: * @param iterable $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@17: $alternatives = []; Chris@0: Chris@17: $collectionParts = []; 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@17: 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@17: 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@14: ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE); 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@17: /** Chris@17: * @internal Chris@17: */ Chris@17: public function isSingleCommand() Chris@17: { Chris@17: return $this->singleCommand; Chris@17: } Chris@17: 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@17: $lines = []; 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@14: Chris@17: $lines[] = \count($lines) ? str_pad($line, $width) : $line; 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@17: $namespaces = []; Chris@0: Chris@0: foreach ($parts as $part) { Chris@17: 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@14: Chris@14: private function init() Chris@14: { Chris@14: if ($this->initialized) { Chris@14: return; Chris@14: } Chris@14: $this->initialized = true; Chris@14: Chris@14: foreach ($this->getDefaultCommands() as $command) { Chris@14: $this->add($command); Chris@14: } Chris@14: } Chris@0: }