Application.php 46 KB

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