annotate vendor/symfony/console/Application.php @ 17:129ea1e6d783

Update, including to Drupal core 8.6.10
author Chris Cannam
date Thu, 28 Feb 2019 13:21:36 +0000
parents 1fec387a4317
children af1871eacc83
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of the Symfony package.
Chris@0 5 *
Chris@0 6 * (c) Fabien Potencier <fabien@symfony.com>
Chris@0 7 *
Chris@0 8 * For the full copyright and license information, please view the LICENSE
Chris@0 9 * file that was distributed with this source code.
Chris@0 10 */
Chris@0 11
Chris@0 12 namespace Symfony\Component\Console;
Chris@0 13
Chris@0 14 use Symfony\Component\Console\Command\Command;
Chris@0 15 use Symfony\Component\Console\Command\HelpCommand;
Chris@0 16 use Symfony\Component\Console\Command\ListCommand;
Chris@17 17 use Symfony\Component\Console\CommandLoader\CommandLoaderInterface;
Chris@0 18 use Symfony\Component\Console\Event\ConsoleCommandEvent;
Chris@14 19 use Symfony\Component\Console\Event\ConsoleErrorEvent;
Chris@0 20 use Symfony\Component\Console\Event\ConsoleExceptionEvent;
Chris@0 21 use Symfony\Component\Console\Event\ConsoleTerminateEvent;
Chris@0 22 use Symfony\Component\Console\Exception\CommandNotFoundException;
Chris@17 23 use Symfony\Component\Console\Exception\ExceptionInterface;
Chris@0 24 use Symfony\Component\Console\Exception\LogicException;
Chris@17 25 use Symfony\Component\Console\Formatter\OutputFormatter;
Chris@17 26 use Symfony\Component\Console\Helper\DebugFormatterHelper;
Chris@17 27 use Symfony\Component\Console\Helper\FormatterHelper;
Chris@17 28 use Symfony\Component\Console\Helper\Helper;
Chris@17 29 use Symfony\Component\Console\Helper\HelperSet;
Chris@17 30 use Symfony\Component\Console\Helper\ProcessHelper;
Chris@17 31 use Symfony\Component\Console\Helper\QuestionHelper;
Chris@17 32 use Symfony\Component\Console\Input\ArgvInput;
Chris@17 33 use Symfony\Component\Console\Input\ArrayInput;
Chris@17 34 use Symfony\Component\Console\Input\InputArgument;
Chris@17 35 use Symfony\Component\Console\Input\InputAwareInterface;
Chris@17 36 use Symfony\Component\Console\Input\InputDefinition;
Chris@17 37 use Symfony\Component\Console\Input\InputInterface;
Chris@17 38 use Symfony\Component\Console\Input\InputOption;
Chris@17 39 use Symfony\Component\Console\Input\StreamableInputInterface;
Chris@17 40 use Symfony\Component\Console\Output\ConsoleOutput;
Chris@17 41 use Symfony\Component\Console\Output\ConsoleOutputInterface;
Chris@17 42 use Symfony\Component\Console\Output\OutputInterface;
Chris@14 43 use Symfony\Component\Debug\ErrorHandler;
Chris@0 44 use Symfony\Component\Debug\Exception\FatalThrowableError;
Chris@0 45 use Symfony\Component\EventDispatcher\EventDispatcherInterface;
Chris@0 46
Chris@0 47 /**
Chris@0 48 * An Application is the container for a collection of commands.
Chris@0 49 *
Chris@0 50 * It is the main entry point of a Console application.
Chris@0 51 *
Chris@0 52 * This class is optimized for a standard CLI environment.
Chris@0 53 *
Chris@0 54 * Usage:
Chris@0 55 *
Chris@0 56 * $app = new Application('myapp', '1.0 (stable)');
Chris@0 57 * $app->add(new SimpleCommand());
Chris@0 58 * $app->run();
Chris@0 59 *
Chris@0 60 * @author Fabien Potencier <fabien@symfony.com>
Chris@0 61 */
Chris@0 62 class Application
Chris@0 63 {
Chris@17 64 private $commands = [];
Chris@0 65 private $wantHelps = false;
Chris@0 66 private $runningCommand;
Chris@0 67 private $name;
Chris@0 68 private $version;
Chris@14 69 private $commandLoader;
Chris@0 70 private $catchExceptions = true;
Chris@0 71 private $autoExit = true;
Chris@0 72 private $definition;
Chris@0 73 private $helperSet;
Chris@0 74 private $dispatcher;
Chris@0 75 private $terminal;
Chris@0 76 private $defaultCommand;
Chris@17 77 private $singleCommand = false;
Chris@14 78 private $initialized;
Chris@0 79
Chris@0 80 /**
Chris@0 81 * @param string $name The name of the application
Chris@0 82 * @param string $version The version of the application
Chris@0 83 */
Chris@0 84 public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
Chris@0 85 {
Chris@0 86 $this->name = $name;
Chris@0 87 $this->version = $version;
Chris@0 88 $this->terminal = new Terminal();
Chris@0 89 $this->defaultCommand = 'list';
Chris@0 90 }
Chris@0 91
Chris@0 92 public function setDispatcher(EventDispatcherInterface $dispatcher)
Chris@0 93 {
Chris@0 94 $this->dispatcher = $dispatcher;
Chris@0 95 }
Chris@0 96
Chris@14 97 public function setCommandLoader(CommandLoaderInterface $commandLoader)
Chris@14 98 {
Chris@14 99 $this->commandLoader = $commandLoader;
Chris@14 100 }
Chris@14 101
Chris@0 102 /**
Chris@0 103 * Runs the current application.
Chris@0 104 *
Chris@0 105 * @return int 0 if everything went fine, or an error code
Chris@0 106 *
Chris@0 107 * @throws \Exception When running fails. Bypass this when {@link setCatchExceptions()}.
Chris@0 108 */
Chris@0 109 public function run(InputInterface $input = null, OutputInterface $output = null)
Chris@0 110 {
Chris@0 111 putenv('LINES='.$this->terminal->getHeight());
Chris@0 112 putenv('COLUMNS='.$this->terminal->getWidth());
Chris@0 113
Chris@0 114 if (null === $input) {
Chris@0 115 $input = new ArgvInput();
Chris@0 116 }
Chris@0 117
Chris@0 118 if (null === $output) {
Chris@0 119 $output = new ConsoleOutput();
Chris@0 120 }
Chris@0 121
Chris@14 122 $renderException = function ($e) use ($output) {
Chris@14 123 if (!$e instanceof \Exception) {
Chris@14 124 $e = class_exists(FatalThrowableError::class) ? new FatalThrowableError($e) : new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
Chris@0 125 }
Chris@0 126 if ($output instanceof ConsoleOutputInterface) {
Chris@0 127 $this->renderException($e, $output->getErrorOutput());
Chris@0 128 } else {
Chris@0 129 $this->renderException($e, $output);
Chris@0 130 }
Chris@14 131 };
Chris@14 132 if ($phpHandler = set_exception_handler($renderException)) {
Chris@14 133 restore_exception_handler();
Chris@17 134 if (!\is_array($phpHandler) || !$phpHandler[0] instanceof ErrorHandler) {
Chris@14 135 $debugHandler = true;
Chris@14 136 } elseif ($debugHandler = $phpHandler[0]->setExceptionHandler($renderException)) {
Chris@14 137 $phpHandler[0]->setExceptionHandler($debugHandler);
Chris@14 138 }
Chris@14 139 }
Chris@14 140
Chris@14 141 if (null !== $this->dispatcher && $this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) {
Chris@14 142 @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 143 }
Chris@14 144
Chris@14 145 $this->configureIO($input, $output);
Chris@14 146
Chris@14 147 try {
Chris@14 148 $exitCode = $this->doRun($input, $output);
Chris@14 149 } catch (\Exception $e) {
Chris@14 150 if (!$this->catchExceptions) {
Chris@14 151 throw $e;
Chris@14 152 }
Chris@14 153
Chris@14 154 $renderException($e);
Chris@0 155
Chris@0 156 $exitCode = $e->getCode();
Chris@0 157 if (is_numeric($exitCode)) {
Chris@0 158 $exitCode = (int) $exitCode;
Chris@0 159 if (0 === $exitCode) {
Chris@0 160 $exitCode = 1;
Chris@0 161 }
Chris@0 162 } else {
Chris@0 163 $exitCode = 1;
Chris@0 164 }
Chris@14 165 } finally {
Chris@14 166 // if the exception handler changed, keep it
Chris@14 167 // otherwise, unregister $renderException
Chris@14 168 if (!$phpHandler) {
Chris@14 169 if (set_exception_handler($renderException) === $renderException) {
Chris@14 170 restore_exception_handler();
Chris@14 171 }
Chris@14 172 restore_exception_handler();
Chris@14 173 } elseif (!$debugHandler) {
Chris@14 174 $finalHandler = $phpHandler[0]->setExceptionHandler(null);
Chris@14 175 if ($finalHandler !== $renderException) {
Chris@14 176 $phpHandler[0]->setExceptionHandler($finalHandler);
Chris@14 177 }
Chris@14 178 }
Chris@0 179 }
Chris@0 180
Chris@0 181 if ($this->autoExit) {
Chris@0 182 if ($exitCode > 255) {
Chris@0 183 $exitCode = 255;
Chris@0 184 }
Chris@0 185
Chris@0 186 exit($exitCode);
Chris@0 187 }
Chris@0 188
Chris@0 189 return $exitCode;
Chris@0 190 }
Chris@0 191
Chris@0 192 /**
Chris@0 193 * Runs the current application.
Chris@0 194 *
Chris@0 195 * @return int 0 if everything went fine, or an error code
Chris@0 196 */
Chris@0 197 public function doRun(InputInterface $input, OutputInterface $output)
Chris@0 198 {
Chris@17 199 if (true === $input->hasParameterOption(['--version', '-V'], true)) {
Chris@0 200 $output->writeln($this->getLongVersion());
Chris@0 201
Chris@0 202 return 0;
Chris@0 203 }
Chris@0 204
Chris@0 205 $name = $this->getCommandName($input);
Chris@17 206 if (true === $input->hasParameterOption(['--help', '-h'], true)) {
Chris@0 207 if (!$name) {
Chris@0 208 $name = 'help';
Chris@17 209 $input = new ArrayInput(['command_name' => $this->defaultCommand]);
Chris@0 210 } else {
Chris@0 211 $this->wantHelps = true;
Chris@0 212 }
Chris@0 213 }
Chris@0 214
Chris@0 215 if (!$name) {
Chris@0 216 $name = $this->defaultCommand;
Chris@14 217 $definition = $this->getDefinition();
Chris@14 218 $definition->setArguments(array_merge(
Chris@14 219 $definition->getArguments(),
Chris@17 220 [
Chris@14 221 'command' => new InputArgument('command', InputArgument::OPTIONAL, $definition->getArgument('command')->getDescription(), $name),
Chris@17 222 ]
Chris@12 223 ));
Chris@0 224 }
Chris@0 225
Chris@14 226 try {
Chris@14 227 $e = $this->runningCommand = null;
Chris@14 228 // the command name MUST be the first element of the input
Chris@14 229 $command = $this->find($name);
Chris@14 230 } catch (\Exception $e) {
Chris@14 231 } catch (\Throwable $e) {
Chris@14 232 }
Chris@14 233 if (null !== $e) {
Chris@14 234 if (null !== $this->dispatcher) {
Chris@14 235 $event = new ConsoleErrorEvent($input, $output, $e);
Chris@14 236 $this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
Chris@14 237 $e = $event->getError();
Chris@14 238
Chris@14 239 if (0 === $event->getExitCode()) {
Chris@14 240 return 0;
Chris@14 241 }
Chris@14 242 }
Chris@14 243
Chris@14 244 throw $e;
Chris@14 245 }
Chris@0 246
Chris@0 247 $this->runningCommand = $command;
Chris@0 248 $exitCode = $this->doRunCommand($command, $input, $output);
Chris@0 249 $this->runningCommand = null;
Chris@0 250
Chris@0 251 return $exitCode;
Chris@0 252 }
Chris@0 253
Chris@0 254 public function setHelperSet(HelperSet $helperSet)
Chris@0 255 {
Chris@0 256 $this->helperSet = $helperSet;
Chris@0 257 }
Chris@0 258
Chris@0 259 /**
Chris@0 260 * Get the helper set associated with the command.
Chris@0 261 *
Chris@0 262 * @return HelperSet The HelperSet instance associated with this command
Chris@0 263 */
Chris@0 264 public function getHelperSet()
Chris@0 265 {
Chris@14 266 if (!$this->helperSet) {
Chris@14 267 $this->helperSet = $this->getDefaultHelperSet();
Chris@14 268 }
Chris@14 269
Chris@0 270 return $this->helperSet;
Chris@0 271 }
Chris@0 272
Chris@0 273 public function setDefinition(InputDefinition $definition)
Chris@0 274 {
Chris@0 275 $this->definition = $definition;
Chris@0 276 }
Chris@0 277
Chris@0 278 /**
Chris@0 279 * Gets the InputDefinition related to this Application.
Chris@0 280 *
Chris@0 281 * @return InputDefinition The InputDefinition instance
Chris@0 282 */
Chris@0 283 public function getDefinition()
Chris@0 284 {
Chris@14 285 if (!$this->definition) {
Chris@14 286 $this->definition = $this->getDefaultInputDefinition();
Chris@14 287 }
Chris@14 288
Chris@0 289 if ($this->singleCommand) {
Chris@0 290 $inputDefinition = $this->definition;
Chris@0 291 $inputDefinition->setArguments();
Chris@0 292
Chris@0 293 return $inputDefinition;
Chris@0 294 }
Chris@0 295
Chris@0 296 return $this->definition;
Chris@0 297 }
Chris@0 298
Chris@0 299 /**
Chris@0 300 * Gets the help message.
Chris@0 301 *
Chris@0 302 * @return string A help message
Chris@0 303 */
Chris@0 304 public function getHelp()
Chris@0 305 {
Chris@0 306 return $this->getLongVersion();
Chris@0 307 }
Chris@0 308
Chris@0 309 /**
Chris@0 310 * Gets whether to catch exceptions or not during commands execution.
Chris@0 311 *
Chris@0 312 * @return bool Whether to catch exceptions or not during commands execution
Chris@0 313 */
Chris@0 314 public function areExceptionsCaught()
Chris@0 315 {
Chris@0 316 return $this->catchExceptions;
Chris@0 317 }
Chris@0 318
Chris@0 319 /**
Chris@0 320 * Sets whether to catch exceptions or not during commands execution.
Chris@0 321 *
Chris@0 322 * @param bool $boolean Whether to catch exceptions or not during commands execution
Chris@0 323 */
Chris@0 324 public function setCatchExceptions($boolean)
Chris@0 325 {
Chris@0 326 $this->catchExceptions = (bool) $boolean;
Chris@0 327 }
Chris@0 328
Chris@0 329 /**
Chris@0 330 * Gets whether to automatically exit after a command execution or not.
Chris@0 331 *
Chris@0 332 * @return bool Whether to automatically exit after a command execution or not
Chris@0 333 */
Chris@0 334 public function isAutoExitEnabled()
Chris@0 335 {
Chris@0 336 return $this->autoExit;
Chris@0 337 }
Chris@0 338
Chris@0 339 /**
Chris@0 340 * Sets whether to automatically exit after a command execution or not.
Chris@0 341 *
Chris@0 342 * @param bool $boolean Whether to automatically exit after a command execution or not
Chris@0 343 */
Chris@0 344 public function setAutoExit($boolean)
Chris@0 345 {
Chris@0 346 $this->autoExit = (bool) $boolean;
Chris@0 347 }
Chris@0 348
Chris@0 349 /**
Chris@0 350 * Gets the name of the application.
Chris@0 351 *
Chris@0 352 * @return string The application name
Chris@0 353 */
Chris@0 354 public function getName()
Chris@0 355 {
Chris@0 356 return $this->name;
Chris@0 357 }
Chris@0 358
Chris@0 359 /**
Chris@0 360 * Sets the application name.
Chris@0 361 *
Chris@0 362 * @param string $name The application name
Chris@0 363 */
Chris@0 364 public function setName($name)
Chris@0 365 {
Chris@0 366 $this->name = $name;
Chris@0 367 }
Chris@0 368
Chris@0 369 /**
Chris@0 370 * Gets the application version.
Chris@0 371 *
Chris@0 372 * @return string The application version
Chris@0 373 */
Chris@0 374 public function getVersion()
Chris@0 375 {
Chris@0 376 return $this->version;
Chris@0 377 }
Chris@0 378
Chris@0 379 /**
Chris@0 380 * Sets the application version.
Chris@0 381 *
Chris@0 382 * @param string $version The application version
Chris@0 383 */
Chris@0 384 public function setVersion($version)
Chris@0 385 {
Chris@0 386 $this->version = $version;
Chris@0 387 }
Chris@0 388
Chris@0 389 /**
Chris@0 390 * Returns the long version of the application.
Chris@0 391 *
Chris@0 392 * @return string The long application version
Chris@0 393 */
Chris@0 394 public function getLongVersion()
Chris@0 395 {
Chris@0 396 if ('UNKNOWN' !== $this->getName()) {
Chris@0 397 if ('UNKNOWN' !== $this->getVersion()) {
Chris@0 398 return sprintf('%s <info>%s</info>', $this->getName(), $this->getVersion());
Chris@0 399 }
Chris@0 400
Chris@0 401 return $this->getName();
Chris@0 402 }
Chris@0 403
Chris@0 404 return 'Console Tool';
Chris@0 405 }
Chris@0 406
Chris@0 407 /**
Chris@0 408 * Registers a new command.
Chris@0 409 *
Chris@0 410 * @param string $name The command name
Chris@0 411 *
Chris@0 412 * @return Command The newly created command
Chris@0 413 */
Chris@0 414 public function register($name)
Chris@0 415 {
Chris@0 416 return $this->add(new Command($name));
Chris@0 417 }
Chris@0 418
Chris@0 419 /**
Chris@0 420 * Adds an array of command objects.
Chris@0 421 *
Chris@0 422 * If a Command is not enabled it will not be added.
Chris@0 423 *
Chris@0 424 * @param Command[] $commands An array of commands
Chris@0 425 */
Chris@0 426 public function addCommands(array $commands)
Chris@0 427 {
Chris@0 428 foreach ($commands as $command) {
Chris@0 429 $this->add($command);
Chris@0 430 }
Chris@0 431 }
Chris@0 432
Chris@0 433 /**
Chris@0 434 * Adds a command object.
Chris@0 435 *
Chris@0 436 * If a command with the same name already exists, it will be overridden.
Chris@0 437 * If the command is not enabled it will not be added.
Chris@0 438 *
Chris@0 439 * @return Command|null The registered command if enabled or null
Chris@0 440 */
Chris@0 441 public function add(Command $command)
Chris@0 442 {
Chris@14 443 $this->init();
Chris@14 444
Chris@0 445 $command->setApplication($this);
Chris@0 446
Chris@0 447 if (!$command->isEnabled()) {
Chris@0 448 $command->setApplication(null);
Chris@0 449
Chris@0 450 return;
Chris@0 451 }
Chris@0 452
Chris@0 453 if (null === $command->getDefinition()) {
Chris@17 454 throw new LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', \get_class($command)));
Chris@0 455 }
Chris@0 456
Chris@14 457 if (!$command->getName()) {
Chris@17 458 throw new LogicException(sprintf('The command defined in "%s" cannot have an empty name.', \get_class($command)));
Chris@14 459 }
Chris@14 460
Chris@0 461 $this->commands[$command->getName()] = $command;
Chris@0 462
Chris@0 463 foreach ($command->getAliases() as $alias) {
Chris@0 464 $this->commands[$alias] = $command;
Chris@0 465 }
Chris@0 466
Chris@0 467 return $command;
Chris@0 468 }
Chris@0 469
Chris@0 470 /**
Chris@0 471 * Returns a registered command by name or alias.
Chris@0 472 *
Chris@0 473 * @param string $name The command name or alias
Chris@0 474 *
Chris@0 475 * @return Command A Command object
Chris@0 476 *
Chris@0 477 * @throws CommandNotFoundException When given command name does not exist
Chris@0 478 */
Chris@0 479 public function get($name)
Chris@0 480 {
Chris@14 481 $this->init();
Chris@14 482
Chris@14 483 if (!$this->has($name)) {
Chris@0 484 throw new CommandNotFoundException(sprintf('The command "%s" does not exist.', $name));
Chris@0 485 }
Chris@0 486
Chris@0 487 $command = $this->commands[$name];
Chris@0 488
Chris@0 489 if ($this->wantHelps) {
Chris@0 490 $this->wantHelps = false;
Chris@0 491
Chris@0 492 $helpCommand = $this->get('help');
Chris@0 493 $helpCommand->setCommand($command);
Chris@0 494
Chris@0 495 return $helpCommand;
Chris@0 496 }
Chris@0 497
Chris@0 498 return $command;
Chris@0 499 }
Chris@0 500
Chris@0 501 /**
Chris@0 502 * Returns true if the command exists, false otherwise.
Chris@0 503 *
Chris@0 504 * @param string $name The command name or alias
Chris@0 505 *
Chris@0 506 * @return bool true if the command exists, false otherwise
Chris@0 507 */
Chris@0 508 public function has($name)
Chris@0 509 {
Chris@14 510 $this->init();
Chris@14 511
Chris@14 512 return isset($this->commands[$name]) || ($this->commandLoader && $this->commandLoader->has($name) && $this->add($this->commandLoader->get($name)));
Chris@0 513 }
Chris@0 514
Chris@0 515 /**
Chris@0 516 * Returns an array of all unique namespaces used by currently registered commands.
Chris@0 517 *
Chris@0 518 * It does not return the global namespace which always exists.
Chris@0 519 *
Chris@0 520 * @return string[] An array of namespaces
Chris@0 521 */
Chris@0 522 public function getNamespaces()
Chris@0 523 {
Chris@17 524 $namespaces = [];
Chris@0 525 foreach ($this->all() as $command) {
Chris@0 526 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
Chris@0 527
Chris@0 528 foreach ($command->getAliases() as $alias) {
Chris@0 529 $namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias));
Chris@0 530 }
Chris@0 531 }
Chris@0 532
Chris@0 533 return array_values(array_unique(array_filter($namespaces)));
Chris@0 534 }
Chris@0 535
Chris@0 536 /**
Chris@0 537 * Finds a registered namespace by a name or an abbreviation.
Chris@0 538 *
Chris@0 539 * @param string $namespace A namespace or abbreviation to search for
Chris@0 540 *
Chris@0 541 * @return string A registered namespace
Chris@0 542 *
Chris@0 543 * @throws CommandNotFoundException When namespace is incorrect or ambiguous
Chris@0 544 */
Chris@0 545 public function findNamespace($namespace)
Chris@0 546 {
Chris@0 547 $allNamespaces = $this->getNamespaces();
Chris@0 548 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $namespace);
Chris@0 549 $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
Chris@0 550
Chris@0 551 if (empty($namespaces)) {
Chris@0 552 $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
Chris@0 553
Chris@0 554 if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
Chris@17 555 if (1 == \count($alternatives)) {
Chris@0 556 $message .= "\n\nDid you mean this?\n ";
Chris@0 557 } else {
Chris@0 558 $message .= "\n\nDid you mean one of these?\n ";
Chris@0 559 }
Chris@0 560
Chris@0 561 $message .= implode("\n ", $alternatives);
Chris@0 562 }
Chris@0 563
Chris@0 564 throw new CommandNotFoundException($message, $alternatives);
Chris@0 565 }
Chris@0 566
Chris@17 567 $exact = \in_array($namespace, $namespaces, true);
Chris@17 568 if (\count($namespaces) > 1 && !$exact) {
Chris@14 569 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 570 }
Chris@0 571
Chris@0 572 return $exact ? $namespace : reset($namespaces);
Chris@0 573 }
Chris@0 574
Chris@0 575 /**
Chris@0 576 * Finds a command by name or alias.
Chris@0 577 *
Chris@0 578 * Contrary to get, this command tries to find the best
Chris@0 579 * match if you give it an abbreviation of a name or alias.
Chris@0 580 *
Chris@0 581 * @param string $name A command name or a command alias
Chris@0 582 *
Chris@0 583 * @return Command A Command instance
Chris@0 584 *
Chris@0 585 * @throws CommandNotFoundException When command name is incorrect or ambiguous
Chris@0 586 */
Chris@0 587 public function find($name)
Chris@0 588 {
Chris@14 589 $this->init();
Chris@14 590
Chris@17 591 $aliases = [];
Chris@14 592 $allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
Chris@0 593 $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
Chris@0 594 $commands = preg_grep('{^'.$expr.'}', $allCommands);
Chris@0 595
Chris@14 596 if (empty($commands)) {
Chris@14 597 $commands = preg_grep('{^'.$expr.'}i', $allCommands);
Chris@14 598 }
Chris@14 599
Chris@14 600 // if no commands matched or we just matched namespaces
Chris@17 601 if (empty($commands) || \count(preg_grep('{^'.$expr.'$}i', $commands)) < 1) {
Chris@0 602 if (false !== $pos = strrpos($name, ':')) {
Chris@0 603 // check if a namespace exists and contains commands
Chris@0 604 $this->findNamespace(substr($name, 0, $pos));
Chris@0 605 }
Chris@0 606
Chris@0 607 $message = sprintf('Command "%s" is not defined.', $name);
Chris@0 608
Chris@0 609 if ($alternatives = $this->findAlternatives($name, $allCommands)) {
Chris@17 610 if (1 == \count($alternatives)) {
Chris@0 611 $message .= "\n\nDid you mean this?\n ";
Chris@0 612 } else {
Chris@0 613 $message .= "\n\nDid you mean one of these?\n ";
Chris@0 614 }
Chris@0 615 $message .= implode("\n ", $alternatives);
Chris@0 616 }
Chris@0 617
Chris@0 618 throw new CommandNotFoundException($message, $alternatives);
Chris@0 619 }
Chris@0 620
Chris@0 621 // filter out aliases for commands which are already on the list
Chris@17 622 if (\count($commands) > 1) {
Chris@14 623 $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands;
Chris@14 624 $commands = array_unique(array_filter($commands, function ($nameOrAlias) use ($commandList, $commands, &$aliases) {
Chris@14 625 $commandName = $commandList[$nameOrAlias] instanceof Command ? $commandList[$nameOrAlias]->getName() : $nameOrAlias;
Chris@14 626 $aliases[$nameOrAlias] = $commandName;
Chris@0 627
Chris@17 628 return $commandName === $nameOrAlias || !\in_array($commandName, $commands);
Chris@14 629 }));
Chris@0 630 }
Chris@0 631
Chris@17 632 $exact = \in_array($name, $commands, true) || isset($aliases[$name]);
Chris@17 633 if (\count($commands) > 1 && !$exact) {
Chris@14 634 $usableWidth = $this->terminal->getWidth() - 10;
Chris@14 635 $abbrevs = array_values($commands);
Chris@14 636 $maxLen = 0;
Chris@14 637 foreach ($abbrevs as $abbrev) {
Chris@14 638 $maxLen = max(Helper::strlen($abbrev), $maxLen);
Chris@14 639 }
Chris@14 640 $abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen) {
Chris@14 641 if (!$commandList[$cmd] instanceof Command) {
Chris@14 642 return $cmd;
Chris@14 643 }
Chris@14 644 $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription();
Chris@0 645
Chris@14 646 return Helper::strlen($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev;
Chris@14 647 }, array_values($commands));
Chris@14 648 $suggestions = $this->getAbbreviationSuggestions($abbrevs);
Chris@14 649
Chris@14 650 throw new CommandNotFoundException(sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s", $name, $suggestions), array_values($commands));
Chris@0 651 }
Chris@0 652
Chris@0 653 return $this->get($exact ? $name : reset($commands));
Chris@0 654 }
Chris@0 655
Chris@0 656 /**
Chris@0 657 * Gets the commands (registered in the given namespace if provided).
Chris@0 658 *
Chris@0 659 * The array keys are the full names and the values the command instances.
Chris@0 660 *
Chris@0 661 * @param string $namespace A namespace name
Chris@0 662 *
Chris@0 663 * @return Command[] An array of Command instances
Chris@0 664 */
Chris@0 665 public function all($namespace = null)
Chris@0 666 {
Chris@14 667 $this->init();
Chris@14 668
Chris@0 669 if (null === $namespace) {
Chris@14 670 if (!$this->commandLoader) {
Chris@14 671 return $this->commands;
Chris@14 672 }
Chris@14 673
Chris@14 674 $commands = $this->commands;
Chris@14 675 foreach ($this->commandLoader->getNames() as $name) {
Chris@14 676 if (!isset($commands[$name]) && $this->has($name)) {
Chris@14 677 $commands[$name] = $this->get($name);
Chris@14 678 }
Chris@14 679 }
Chris@14 680
Chris@14 681 return $commands;
Chris@0 682 }
Chris@0 683
Chris@17 684 $commands = [];
Chris@0 685 foreach ($this->commands as $name => $command) {
Chris@0 686 if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
Chris@0 687 $commands[$name] = $command;
Chris@0 688 }
Chris@0 689 }
Chris@0 690
Chris@14 691 if ($this->commandLoader) {
Chris@14 692 foreach ($this->commandLoader->getNames() as $name) {
Chris@14 693 if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) {
Chris@14 694 $commands[$name] = $this->get($name);
Chris@14 695 }
Chris@14 696 }
Chris@14 697 }
Chris@14 698
Chris@0 699 return $commands;
Chris@0 700 }
Chris@0 701
Chris@0 702 /**
Chris@0 703 * Returns an array of possible abbreviations given a set of names.
Chris@0 704 *
Chris@0 705 * @param array $names An array of names
Chris@0 706 *
Chris@0 707 * @return array An array of abbreviations
Chris@0 708 */
Chris@0 709 public static function getAbbreviations($names)
Chris@0 710 {
Chris@17 711 $abbrevs = [];
Chris@0 712 foreach ($names as $name) {
Chris@17 713 for ($len = \strlen($name); $len > 0; --$len) {
Chris@0 714 $abbrev = substr($name, 0, $len);
Chris@0 715 $abbrevs[$abbrev][] = $name;
Chris@0 716 }
Chris@0 717 }
Chris@0 718
Chris@0 719 return $abbrevs;
Chris@0 720 }
Chris@0 721
Chris@0 722 /**
Chris@0 723 * Renders a caught exception.
Chris@0 724 */
Chris@0 725 public function renderException(\Exception $e, OutputInterface $output)
Chris@0 726 {
Chris@0 727 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
Chris@0 728
Chris@14 729 $this->doRenderException($e, $output);
Chris@14 730
Chris@14 731 if (null !== $this->runningCommand) {
Chris@14 732 $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())), OutputInterface::VERBOSITY_QUIET);
Chris@14 733 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
Chris@14 734 }
Chris@14 735 }
Chris@14 736
Chris@14 737 protected function doRenderException(\Exception $e, OutputInterface $output)
Chris@14 738 {
Chris@0 739 do {
Chris@14 740 $message = trim($e->getMessage());
Chris@14 741 if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
Chris@17 742 $title = sprintf(' [%s%s] ', \get_class($e), 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
Chris@14 743 $len = Helper::strlen($title);
Chris@14 744 } else {
Chris@14 745 $len = 0;
Chris@14 746 }
Chris@0 747
Chris@0 748 $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : PHP_INT_MAX;
Chris@0 749 // 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 750 if (\defined('HHVM_VERSION') && $width > 1 << 31) {
Chris@0 751 $width = 1 << 31;
Chris@0 752 }
Chris@17 753 $lines = [];
Chris@17 754 foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) {
Chris@0 755 foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
Chris@0 756 // pre-format lines to get the right string length
Chris@12 757 $lineLength = Helper::strlen($line) + 4;
Chris@17 758 $lines[] = [$line, $lineLength];
Chris@0 759
Chris@0 760 $len = max($lineLength, $len);
Chris@0 761 }
Chris@0 762 }
Chris@0 763
Chris@17 764 $messages = [];
Chris@14 765 if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
Chris@14 766 $messages[] = sprintf('<comment>%s</comment>', OutputFormatter::escape(sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a')));
Chris@14 767 }
Chris@0 768 $messages[] = $emptyLine = sprintf('<error>%s</error>', str_repeat(' ', $len));
Chris@14 769 if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
Chris@14 770 $messages[] = sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::strlen($title))));
Chris@14 771 }
Chris@0 772 foreach ($lines as $line) {
Chris@0 773 $messages[] = sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
Chris@0 774 }
Chris@0 775 $messages[] = $emptyLine;
Chris@0 776 $messages[] = '';
Chris@0 777
Chris@0 778 $output->writeln($messages, OutputInterface::VERBOSITY_QUIET);
Chris@0 779
Chris@0 780 if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
Chris@0 781 $output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
Chris@0 782
Chris@0 783 // exception related properties
Chris@0 784 $trace = $e->getTrace();
Chris@0 785
Chris@17 786 array_unshift($trace, [
Chris@17 787 'function' => '',
Chris@17 788 'file' => $e->getFile() ?: 'n/a',
Chris@17 789 'line' => $e->getLine() ?: 'n/a',
Chris@17 790 'args' => [],
Chris@17 791 ]);
Chris@17 792
Chris@17 793 for ($i = 0, $count = \count($trace); $i < $count; ++$i) {
Chris@0 794 $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
Chris@0 795 $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
Chris@0 796 $function = $trace[$i]['function'];
Chris@0 797 $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
Chris@0 798 $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
Chris@0 799
Chris@0 800 $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line), OutputInterface::VERBOSITY_QUIET);
Chris@0 801 }
Chris@0 802
Chris@0 803 $output->writeln('', OutputInterface::VERBOSITY_QUIET);
Chris@0 804 }
Chris@0 805 } while ($e = $e->getPrevious());
Chris@0 806 }
Chris@0 807
Chris@0 808 /**
Chris@0 809 * Tries to figure out the terminal width in which this application runs.
Chris@0 810 *
Chris@0 811 * @return int|null
Chris@0 812 *
Chris@0 813 * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead.
Chris@0 814 */
Chris@0 815 protected function getTerminalWidth()
Chris@0 816 {
Chris@17 817 @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 818
Chris@0 819 return $this->terminal->getWidth();
Chris@0 820 }
Chris@0 821
Chris@0 822 /**
Chris@0 823 * Tries to figure out the terminal height in which this application runs.
Chris@0 824 *
Chris@0 825 * @return int|null
Chris@0 826 *
Chris@0 827 * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead.
Chris@0 828 */
Chris@0 829 protected function getTerminalHeight()
Chris@0 830 {
Chris@17 831 @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 832
Chris@0 833 return $this->terminal->getHeight();
Chris@0 834 }
Chris@0 835
Chris@0 836 /**
Chris@0 837 * Tries to figure out the terminal dimensions based on the current environment.
Chris@0 838 *
Chris@0 839 * @return array Array containing width and height
Chris@0 840 *
Chris@0 841 * @deprecated since version 3.2, to be removed in 4.0. Create a Terminal instance instead.
Chris@0 842 */
Chris@0 843 public function getTerminalDimensions()
Chris@0 844 {
Chris@17 845 @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 846
Chris@17 847 return [$this->terminal->getWidth(), $this->terminal->getHeight()];
Chris@0 848 }
Chris@0 849
Chris@0 850 /**
Chris@0 851 * Sets terminal dimensions.
Chris@0 852 *
Chris@0 853 * Can be useful to force terminal dimensions for functional tests.
Chris@0 854 *
Chris@0 855 * @param int $width The width
Chris@0 856 * @param int $height The height
Chris@0 857 *
Chris@0 858 * @return $this
Chris@0 859 *
Chris@0 860 * @deprecated since version 3.2, to be removed in 4.0. Set the COLUMNS and LINES env vars instead.
Chris@0 861 */
Chris@0 862 public function setTerminalDimensions($width, $height)
Chris@0 863 {
Chris@17 864 @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 865
Chris@0 866 putenv('COLUMNS='.$width);
Chris@0 867 putenv('LINES='.$height);
Chris@0 868
Chris@0 869 return $this;
Chris@0 870 }
Chris@0 871
Chris@0 872 /**
Chris@0 873 * Configures the input and output instances based on the user arguments and options.
Chris@0 874 */
Chris@0 875 protected function configureIO(InputInterface $input, OutputInterface $output)
Chris@0 876 {
Chris@17 877 if (true === $input->hasParameterOption(['--ansi'], true)) {
Chris@0 878 $output->setDecorated(true);
Chris@17 879 } elseif (true === $input->hasParameterOption(['--no-ansi'], true)) {
Chris@0 880 $output->setDecorated(false);
Chris@0 881 }
Chris@0 882
Chris@17 883 if (true === $input->hasParameterOption(['--no-interaction', '-n'], true)) {
Chris@0 884 $input->setInteractive(false);
Chris@17 885 } elseif (\function_exists('posix_isatty')) {
Chris@0 886 $inputStream = null;
Chris@0 887
Chris@0 888 if ($input instanceof StreamableInputInterface) {
Chris@0 889 $inputStream = $input->getStream();
Chris@0 890 }
Chris@0 891
Chris@0 892 // This check ensures that calling QuestionHelper::setInputStream() works
Chris@0 893 // To be removed in 4.0 (in the same time as QuestionHelper::setInputStream)
Chris@0 894 if (!$inputStream && $this->getHelperSet()->has('question')) {
Chris@0 895 $inputStream = $this->getHelperSet()->get('question')->getInputStream(false);
Chris@0 896 }
Chris@0 897
Chris@0 898 if (!@posix_isatty($inputStream) && false === getenv('SHELL_INTERACTIVE')) {
Chris@0 899 $input->setInteractive(false);
Chris@0 900 }
Chris@0 901 }
Chris@0 902
Chris@14 903 switch ($shellVerbosity = (int) getenv('SHELL_VERBOSITY')) {
Chris@14 904 case -1: $output->setVerbosity(OutputInterface::VERBOSITY_QUIET); break;
Chris@14 905 case 1: $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE); break;
Chris@14 906 case 2: $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE); break;
Chris@14 907 case 3: $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG); break;
Chris@14 908 default: $shellVerbosity = 0; break;
Chris@14 909 }
Chris@14 910
Chris@17 911 if (true === $input->hasParameterOption(['--quiet', '-q'], true)) {
Chris@0 912 $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
Chris@14 913 $shellVerbosity = -1;
Chris@0 914 } else {
Chris@14 915 if ($input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true)) {
Chris@0 916 $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
Chris@14 917 $shellVerbosity = 3;
Chris@14 918 } elseif ($input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true)) {
Chris@0 919 $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
Chris@14 920 $shellVerbosity = 2;
Chris@0 921 } elseif ($input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true)) {
Chris@0 922 $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
Chris@14 923 $shellVerbosity = 1;
Chris@0 924 }
Chris@0 925 }
Chris@14 926
Chris@14 927 if (-1 === $shellVerbosity) {
Chris@14 928 $input->setInteractive(false);
Chris@14 929 }
Chris@14 930
Chris@14 931 putenv('SHELL_VERBOSITY='.$shellVerbosity);
Chris@14 932 $_ENV['SHELL_VERBOSITY'] = $shellVerbosity;
Chris@14 933 $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity;
Chris@0 934 }
Chris@0 935
Chris@0 936 /**
Chris@0 937 * Runs the current command.
Chris@0 938 *
Chris@0 939 * If an event dispatcher has been attached to the application,
Chris@0 940 * events are also dispatched during the life-cycle of the command.
Chris@0 941 *
Chris@0 942 * @return int 0 if everything went fine, or an error code
Chris@0 943 */
Chris@0 944 protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
Chris@0 945 {
Chris@0 946 foreach ($command->getHelperSet() as $helper) {
Chris@0 947 if ($helper instanceof InputAwareInterface) {
Chris@0 948 $helper->setInput($input);
Chris@0 949 }
Chris@0 950 }
Chris@0 951
Chris@0 952 if (null === $this->dispatcher) {
Chris@0 953 return $command->run($input, $output);
Chris@0 954 }
Chris@0 955
Chris@0 956 // bind before the console.command event, so the listeners have access to input options/arguments
Chris@0 957 try {
Chris@0 958 $command->mergeApplicationDefinition();
Chris@0 959 $input->bind($command->getDefinition());
Chris@0 960 } catch (ExceptionInterface $e) {
Chris@0 961 // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
Chris@0 962 }
Chris@0 963
Chris@0 964 $event = new ConsoleCommandEvent($command, $input, $output);
Chris@0 965 $e = null;
Chris@0 966
Chris@0 967 try {
Chris@0 968 $this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
Chris@0 969
Chris@0 970 if ($event->commandShouldRun()) {
Chris@0 971 $exitCode = $command->run($input, $output);
Chris@0 972 } else {
Chris@0 973 $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
Chris@0 974 }
Chris@0 975 } catch (\Exception $e) {
Chris@0 976 } catch (\Throwable $e) {
Chris@0 977 }
Chris@0 978 if (null !== $e) {
Chris@14 979 if ($this->dispatcher->hasListeners(ConsoleEvents::EXCEPTION)) {
Chris@14 980 $x = $e instanceof \Exception ? $e : new FatalThrowableError($e);
Chris@14 981 $event = new ConsoleExceptionEvent($command, $input, $output, $x, $x->getCode());
Chris@14 982 $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
Chris@0 983
Chris@14 984 if ($x !== $event->getException()) {
Chris@14 985 $e = $event->getException();
Chris@14 986 }
Chris@0 987 }
Chris@14 988 $event = new ConsoleErrorEvent($input, $output, $e, $command);
Chris@14 989 $this->dispatcher->dispatch(ConsoleEvents::ERROR, $event);
Chris@14 990 $e = $event->getError();
Chris@14 991
Chris@14 992 if (0 === $exitCode = $event->getExitCode()) {
Chris@14 993 $e = null;
Chris@14 994 }
Chris@0 995 }
Chris@0 996
Chris@0 997 $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
Chris@0 998 $this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
Chris@0 999
Chris@0 1000 if (null !== $e) {
Chris@0 1001 throw $e;
Chris@0 1002 }
Chris@0 1003
Chris@0 1004 return $event->getExitCode();
Chris@0 1005 }
Chris@0 1006
Chris@0 1007 /**
Chris@0 1008 * Gets the name of the command based on input.
Chris@0 1009 *
Chris@0 1010 * @return string The command name
Chris@0 1011 */
Chris@0 1012 protected function getCommandName(InputInterface $input)
Chris@0 1013 {
Chris@0 1014 return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument();
Chris@0 1015 }
Chris@0 1016
Chris@0 1017 /**
Chris@0 1018 * Gets the default input definition.
Chris@0 1019 *
Chris@0 1020 * @return InputDefinition An InputDefinition instance
Chris@0 1021 */
Chris@0 1022 protected function getDefaultInputDefinition()
Chris@0 1023 {
Chris@17 1024 return new InputDefinition([
Chris@0 1025 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
Chris@0 1026
Chris@0 1027 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
Chris@0 1028 new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
Chris@0 1029 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 1030 new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
Chris@0 1031 new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
Chris@0 1032 new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
Chris@0 1033 new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
Chris@17 1034 ]);
Chris@0 1035 }
Chris@0 1036
Chris@0 1037 /**
Chris@0 1038 * Gets the default commands that should always be available.
Chris@0 1039 *
Chris@0 1040 * @return Command[] An array of default Command instances
Chris@0 1041 */
Chris@0 1042 protected function getDefaultCommands()
Chris@0 1043 {
Chris@17 1044 return [new HelpCommand(), new ListCommand()];
Chris@0 1045 }
Chris@0 1046
Chris@0 1047 /**
Chris@0 1048 * Gets the default helper set with the helpers that should always be available.
Chris@0 1049 *
Chris@0 1050 * @return HelperSet A HelperSet instance
Chris@0 1051 */
Chris@0 1052 protected function getDefaultHelperSet()
Chris@0 1053 {
Chris@17 1054 return new HelperSet([
Chris@0 1055 new FormatterHelper(),
Chris@0 1056 new DebugFormatterHelper(),
Chris@0 1057 new ProcessHelper(),
Chris@0 1058 new QuestionHelper(),
Chris@17 1059 ]);
Chris@0 1060 }
Chris@0 1061
Chris@0 1062 /**
Chris@0 1063 * Returns abbreviated suggestions in string format.
Chris@0 1064 *
Chris@0 1065 * @param array $abbrevs Abbreviated suggestions to convert
Chris@0 1066 *
Chris@0 1067 * @return string A formatted string of abbreviated suggestions
Chris@0 1068 */
Chris@0 1069 private function getAbbreviationSuggestions($abbrevs)
Chris@0 1070 {
Chris@14 1071 return ' '.implode("\n ", $abbrevs);
Chris@0 1072 }
Chris@0 1073
Chris@0 1074 /**
Chris@0 1075 * Returns the namespace part of the command name.
Chris@0 1076 *
Chris@0 1077 * This method is not part of public API and should not be used directly.
Chris@0 1078 *
Chris@0 1079 * @param string $name The full name of the command
Chris@0 1080 * @param string $limit The maximum number of parts of the namespace
Chris@0 1081 *
Chris@0 1082 * @return string The namespace of the command
Chris@0 1083 */
Chris@0 1084 public function extractNamespace($name, $limit = null)
Chris@0 1085 {
Chris@0 1086 $parts = explode(':', $name);
Chris@0 1087 array_pop($parts);
Chris@0 1088
Chris@17 1089 return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit));
Chris@0 1090 }
Chris@0 1091
Chris@0 1092 /**
Chris@0 1093 * Finds alternative of $name among $collection,
Chris@0 1094 * if nothing is found in $collection, try in $abbrevs.
Chris@0 1095 *
Chris@14 1096 * @param string $name The string
Chris@14 1097 * @param iterable $collection The collection
Chris@0 1098 *
Chris@0 1099 * @return string[] A sorted array of similar string
Chris@0 1100 */
Chris@0 1101 private function findAlternatives($name, $collection)
Chris@0 1102 {
Chris@0 1103 $threshold = 1e3;
Chris@17 1104 $alternatives = [];
Chris@0 1105
Chris@17 1106 $collectionParts = [];
Chris@0 1107 foreach ($collection as $item) {
Chris@0 1108 $collectionParts[$item] = explode(':', $item);
Chris@0 1109 }
Chris@0 1110
Chris@0 1111 foreach (explode(':', $name) as $i => $subname) {
Chris@0 1112 foreach ($collectionParts as $collectionName => $parts) {
Chris@0 1113 $exists = isset($alternatives[$collectionName]);
Chris@0 1114 if (!isset($parts[$i]) && $exists) {
Chris@0 1115 $alternatives[$collectionName] += $threshold;
Chris@0 1116 continue;
Chris@0 1117 } elseif (!isset($parts[$i])) {
Chris@0 1118 continue;
Chris@0 1119 }
Chris@0 1120
Chris@0 1121 $lev = levenshtein($subname, $parts[$i]);
Chris@17 1122 if ($lev <= \strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
Chris@0 1123 $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
Chris@0 1124 } elseif ($exists) {
Chris@0 1125 $alternatives[$collectionName] += $threshold;
Chris@0 1126 }
Chris@0 1127 }
Chris@0 1128 }
Chris@0 1129
Chris@0 1130 foreach ($collection as $item) {
Chris@0 1131 $lev = levenshtein($name, $item);
Chris@17 1132 if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) {
Chris@0 1133 $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
Chris@0 1134 }
Chris@0 1135 }
Chris@0 1136
Chris@0 1137 $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2 * $threshold; });
Chris@14 1138 ksort($alternatives, SORT_NATURAL | SORT_FLAG_CASE);
Chris@0 1139
Chris@0 1140 return array_keys($alternatives);
Chris@0 1141 }
Chris@0 1142
Chris@0 1143 /**
Chris@0 1144 * Sets the default Command name.
Chris@0 1145 *
Chris@0 1146 * @param string $commandName The Command name
Chris@0 1147 * @param bool $isSingleCommand Set to true if there is only one command in this application
Chris@0 1148 *
Chris@0 1149 * @return self
Chris@0 1150 */
Chris@0 1151 public function setDefaultCommand($commandName, $isSingleCommand = false)
Chris@0 1152 {
Chris@0 1153 $this->defaultCommand = $commandName;
Chris@0 1154
Chris@0 1155 if ($isSingleCommand) {
Chris@0 1156 // Ensure the command exist
Chris@0 1157 $this->find($commandName);
Chris@0 1158
Chris@0 1159 $this->singleCommand = true;
Chris@0 1160 }
Chris@0 1161
Chris@0 1162 return $this;
Chris@0 1163 }
Chris@0 1164
Chris@17 1165 /**
Chris@17 1166 * @internal
Chris@17 1167 */
Chris@17 1168 public function isSingleCommand()
Chris@17 1169 {
Chris@17 1170 return $this->singleCommand;
Chris@17 1171 }
Chris@17 1172
Chris@0 1173 private function splitStringByWidth($string, $width)
Chris@0 1174 {
Chris@0 1175 // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
Chris@0 1176 // additionally, array_slice() is not enough as some character has doubled width.
Chris@0 1177 // we need a function to split string not by character count but by string width
Chris@0 1178 if (false === $encoding = mb_detect_encoding($string, null, true)) {
Chris@0 1179 return str_split($string, $width);
Chris@0 1180 }
Chris@0 1181
Chris@0 1182 $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
Chris@17 1183 $lines = [];
Chris@0 1184 $line = '';
Chris@0 1185 foreach (preg_split('//u', $utf8String) as $char) {
Chris@0 1186 // test if $char could be appended to current line
Chris@0 1187 if (mb_strwidth($line.$char, 'utf8') <= $width) {
Chris@0 1188 $line .= $char;
Chris@0 1189 continue;
Chris@0 1190 }
Chris@0 1191 // if not, push current line to array and make new line
Chris@0 1192 $lines[] = str_pad($line, $width);
Chris@0 1193 $line = $char;
Chris@0 1194 }
Chris@14 1195
Chris@17 1196 $lines[] = \count($lines) ? str_pad($line, $width) : $line;
Chris@0 1197
Chris@0 1198 mb_convert_variables($encoding, 'utf8', $lines);
Chris@0 1199
Chris@0 1200 return $lines;
Chris@0 1201 }
Chris@0 1202
Chris@0 1203 /**
Chris@0 1204 * Returns all namespaces of the command name.
Chris@0 1205 *
Chris@0 1206 * @param string $name The full name of the command
Chris@0 1207 *
Chris@0 1208 * @return string[] The namespaces of the command
Chris@0 1209 */
Chris@0 1210 private function extractAllNamespaces($name)
Chris@0 1211 {
Chris@0 1212 // -1 as third argument is needed to skip the command short name when exploding
Chris@0 1213 $parts = explode(':', $name, -1);
Chris@17 1214 $namespaces = [];
Chris@0 1215
Chris@0 1216 foreach ($parts as $part) {
Chris@17 1217 if (\count($namespaces)) {
Chris@0 1218 $namespaces[] = end($namespaces).':'.$part;
Chris@0 1219 } else {
Chris@0 1220 $namespaces[] = $part;
Chris@0 1221 }
Chris@0 1222 }
Chris@0 1223
Chris@0 1224 return $namespaces;
Chris@0 1225 }
Chris@14 1226
Chris@14 1227 private function init()
Chris@14 1228 {
Chris@14 1229 if ($this->initialized) {
Chris@14 1230 return;
Chris@14 1231 }
Chris@14 1232 $this->initialized = true;
Chris@14 1233
Chris@14 1234 foreach ($this->getDefaultCommands() as $command) {
Chris@14 1235 $this->add($command);
Chris@14 1236 }
Chris@14 1237 }
Chris@0 1238 }