annotate vendor/symfony/console/Application.php @ 8:50b0d041100e

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