Application.php 46 KB

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