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