Application.php 48 KB

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