Application.php 47 KB

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