annotate vendor/symfony/console/Application.php @ 19:fa3358dc1485 tip

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