Application.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361
  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. * @deprecated since Symfony 7.4, use Application::addCommand() instead
  484. */
  485. public function add(Command $command): ?Command
  486. {
  487. trigger_deprecation('symfony/console', '7.4', 'The "%s()" method is deprecated and will be removed in Symfony 8.0, use "%s::addCommand()" instead.', __METHOD__, self::class);
  488. return $this->addCommand($command);
  489. }
  490. /**
  491. * Adds a command object.
  492. *
  493. * If a command with the same name already exists, it will be overridden.
  494. * If the command is not enabled it will not be added.
  495. */
  496. public function addCommand(callable|Command $command): ?Command
  497. {
  498. $this->init();
  499. if (!$command instanceof Command) {
  500. $command = new Command(null, $command);
  501. }
  502. $command->setApplication($this);
  503. if (!$command->isEnabled()) {
  504. $command->setApplication(null);
  505. return null;
  506. }
  507. if (!$command instanceof LazyCommand) {
  508. // Will throw if the command is not correctly initialized.
  509. $command->getDefinition();
  510. }
  511. if (!$command->getName()) {
  512. throw new LogicException(\sprintf('The command defined in "%s" cannot have an empty name.', get_debug_type($command)));
  513. }
  514. $this->commands[$command->getName()] = $command;
  515. foreach ($command->getAliases() as $alias) {
  516. $this->commands[$alias] = $command;
  517. }
  518. return $command;
  519. }
  520. /**
  521. * Returns a registered command by name or alias.
  522. *
  523. * @throws CommandNotFoundException When given command name does not exist
  524. */
  525. public function get(string $name): Command
  526. {
  527. $this->init();
  528. if (!$this->has($name)) {
  529. throw new CommandNotFoundException(\sprintf('The command "%s" does not exist.', $name));
  530. }
  531. // When the command has a different name than the one used at the command loader level
  532. if (!isset($this->commands[$name])) {
  533. 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));
  534. }
  535. $command = $this->commands[$name];
  536. if ($this->wantHelps) {
  537. $this->wantHelps = false;
  538. $helpCommand = $this->get('help');
  539. $helpCommand->setCommand($command);
  540. return $helpCommand;
  541. }
  542. return $command;
  543. }
  544. /**
  545. * Returns true if the command exists, false otherwise.
  546. */
  547. public function has(string $name): bool
  548. {
  549. $this->init();
  550. return isset($this->commands[$name]) || ($this->commandLoader?->has($name) && $this->addCommand($this->commandLoader->get($name)));
  551. }
  552. /**
  553. * Returns an array of all unique namespaces used by currently registered commands.
  554. *
  555. * It does not return the global namespace which always exists.
  556. *
  557. * @return string[]
  558. */
  559. public function getNamespaces(): array
  560. {
  561. $namespaces = [];
  562. foreach ($this->all() as $command) {
  563. if ($command->isHidden()) {
  564. continue;
  565. }
  566. $namespaces[] = $this->extractAllNamespaces($command->getName());
  567. foreach ($command->getAliases() as $alias) {
  568. $namespaces[] = $this->extractAllNamespaces($alias);
  569. }
  570. }
  571. return array_values(array_unique(array_filter(array_merge([], ...$namespaces))));
  572. }
  573. /**
  574. * Finds a registered namespace by a name or an abbreviation.
  575. *
  576. * @throws NamespaceNotFoundException When namespace is incorrect or ambiguous
  577. */
  578. public function findNamespace(string $namespace): string
  579. {
  580. $allNamespaces = $this->getNamespaces();
  581. $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $namespace))).'[^:]*';
  582. $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
  583. if (!$namespaces) {
  584. $message = \sprintf('There are no commands defined in the "%s" namespace.', $namespace);
  585. if ($alternatives = $this->findAlternatives($namespace, $allNamespaces)) {
  586. if (1 == \count($alternatives)) {
  587. $message .= "\n\nDid you mean this?\n ";
  588. } else {
  589. $message .= "\n\nDid you mean one of these?\n ";
  590. }
  591. $message .= implode("\n ", $alternatives);
  592. }
  593. throw new NamespaceNotFoundException($message, $alternatives);
  594. }
  595. $exact = \in_array($namespace, $namespaces, true);
  596. if (\count($namespaces) > 1 && !$exact) {
  597. 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));
  598. }
  599. return $exact ? $namespace : reset($namespaces);
  600. }
  601. /**
  602. * Finds a command by name or alias.
  603. *
  604. * Contrary to get, this command tries to find the best
  605. * match if you give it an abbreviation of a name or alias.
  606. *
  607. * @throws CommandNotFoundException When command name is incorrect or ambiguous
  608. */
  609. public function find(string $name): Command
  610. {
  611. $this->init();
  612. $aliases = [];
  613. foreach ($this->commands as $command) {
  614. foreach ($command->getAliases() as $alias) {
  615. if (!$this->has($alias)) {
  616. $this->commands[$alias] = $command;
  617. }
  618. }
  619. }
  620. if ($this->has($name)) {
  621. return $this->get($name);
  622. }
  623. $allCommands = $this->commandLoader ? array_merge($this->commandLoader->getNames(), array_keys($this->commands)) : array_keys($this->commands);
  624. $expr = implode('[^:]*:', array_map('preg_quote', explode(':', $name))).'[^:]*';
  625. $commands = preg_grep('{^'.$expr.'}', $allCommands);
  626. if (!$commands) {
  627. $commands = preg_grep('{^'.$expr.'}i', $allCommands);
  628. }
  629. // if no commands matched or we just matched namespaces
  630. if (!$commands || \count(preg_grep('{^'.$expr.'$}i', $commands)) < 1) {
  631. if (false !== $pos = strrpos($name, ':')) {
  632. // check if a namespace exists and contains commands
  633. $this->findNamespace(substr($name, 0, $pos));
  634. }
  635. $message = \sprintf('Command "%s" is not defined.', $name);
  636. if ($alternatives = $this->findAlternatives($name, $allCommands)) {
  637. $wantHelps = $this->wantHelps;
  638. $this->wantHelps = false;
  639. // remove hidden commands
  640. if ($alternatives = array_filter($alternatives, fn ($name) => !$this->get($name)->isHidden())) {
  641. $message .= \sprintf("\n\nDid you mean %s?\n %s", 1 === \count($alternatives) ? 'this' : 'one of these', implode("\n ", $alternatives));
  642. }
  643. $this->wantHelps = $wantHelps;
  644. }
  645. throw new CommandNotFoundException($message, array_values($alternatives));
  646. }
  647. // filter out aliases for commands which are already on the list
  648. if (\count($commands) > 1) {
  649. $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands;
  650. $commands = array_unique(array_filter($commands, function ($nameOrAlias) use (&$commandList, $commands, &$aliases) {
  651. if (!$commandList[$nameOrAlias] instanceof Command) {
  652. $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias);
  653. }
  654. $commandName = $commandList[$nameOrAlias]->getName();
  655. $aliases[$nameOrAlias] = $commandName;
  656. return $commandName === $nameOrAlias || !\in_array($commandName, $commands, true);
  657. }));
  658. }
  659. // check whether all commands left are aliases to the same one
  660. if (\count($commands) > 1) {
  661. $uniqueCommands = array_unique(array_map(function ($nameOrAlias) use (&$commandList) {
  662. if (!$commandList[$nameOrAlias] instanceof Command) {
  663. $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias);
  664. }
  665. return $commandList[$nameOrAlias]->getName();
  666. }, $commands));
  667. if (1 === \count($uniqueCommands)) {
  668. $commands = [reset($uniqueCommands)];
  669. }
  670. }
  671. if (\count($commands) > 1) {
  672. $usableWidth = $this->terminal->getWidth() - 10;
  673. $abbrevs = array_values($commands);
  674. $maxLen = 0;
  675. foreach ($abbrevs as $abbrev) {
  676. $maxLen = max(Helper::width($abbrev), $maxLen);
  677. }
  678. $abbrevs = array_map(static function ($cmd) use ($commandList, $usableWidth, $maxLen, &$commands) {
  679. if ($commandList[$cmd]->isHidden()) {
  680. unset($commands[array_search($cmd, $commands)]);
  681. return false;
  682. }
  683. $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription();
  684. return Helper::width($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev;
  685. }, array_values($commands));
  686. if (\count($commands) > 1) {
  687. $suggestions = $this->getAbbreviationSuggestions(array_filter($abbrevs));
  688. throw new CommandNotFoundException(\sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $name, $suggestions), array_values($commands));
  689. }
  690. }
  691. $command = $commands ? $this->get(reset($commands)) : null;
  692. if (!$command || $command->isHidden()) {
  693. throw new CommandNotFoundException(\sprintf('The command "%s" does not exist.', $name));
  694. }
  695. return $command;
  696. }
  697. /**
  698. * Gets the commands (registered in the given namespace if provided).
  699. *
  700. * The array keys are the full names and the values the command instances.
  701. *
  702. * @return Command[]
  703. */
  704. public function all(?string $namespace = null): array
  705. {
  706. $this->init();
  707. if (null === $namespace) {
  708. if (!$this->commandLoader) {
  709. return $this->commands;
  710. }
  711. $commands = $this->commands;
  712. foreach ($this->commandLoader->getNames() as $name) {
  713. if (!isset($commands[$name]) && $this->has($name)) {
  714. $commands[$name] = $this->get($name);
  715. }
  716. }
  717. return $commands;
  718. }
  719. $commands = [];
  720. foreach ($this->commands as $name => $command) {
  721. if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
  722. $commands[$name] = $command;
  723. }
  724. }
  725. if ($this->commandLoader) {
  726. foreach ($this->commandLoader->getNames() as $name) {
  727. if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) {
  728. $commands[$name] = $this->get($name);
  729. }
  730. }
  731. }
  732. return $commands;
  733. }
  734. /**
  735. * Returns an array of possible abbreviations given a set of names.
  736. *
  737. * @return string[][]
  738. */
  739. public static function getAbbreviations(array $names): array
  740. {
  741. $abbrevs = [];
  742. foreach ($names as $name) {
  743. for ($len = \strlen($name); $len > 0; --$len) {
  744. $abbrev = substr($name, 0, $len);
  745. $abbrevs[$abbrev][] = $name;
  746. }
  747. }
  748. return $abbrevs;
  749. }
  750. public function renderThrowable(\Throwable $e, OutputInterface $output): void
  751. {
  752. $output->writeln('', OutputInterface::VERBOSITY_QUIET);
  753. $this->doRenderThrowable($e, $output);
  754. if (null !== $this->runningCommand) {
  755. $output->writeln(\sprintf('<info>%s</info>', OutputFormatter::escape(\sprintf($this->runningCommand->getSynopsis(), $this->getName()))), OutputInterface::VERBOSITY_QUIET);
  756. $output->writeln('', OutputInterface::VERBOSITY_QUIET);
  757. }
  758. }
  759. protected function doRenderThrowable(\Throwable $e, OutputInterface $output): void
  760. {
  761. do {
  762. $message = trim($e->getMessage());
  763. if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  764. $class = get_debug_type($e);
  765. $title = \sprintf(' [%s%s] ', $class, 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
  766. $len = Helper::width($title);
  767. } else {
  768. $len = 0;
  769. }
  770. if (str_contains($message, "@anonymous\0")) {
  771. $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);
  772. }
  773. $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : \PHP_INT_MAX;
  774. $lines = [];
  775. foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) {
  776. foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
  777. // pre-format lines to get the right string length
  778. $lineLength = Helper::width($line) + 4;
  779. $lines[] = [$line, $lineLength];
  780. $len = max($lineLength, $len);
  781. }
  782. }
  783. $messages = [];
  784. if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  785. $messages[] = \sprintf('<comment>%s</comment>', OutputFormatter::escape(\sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a')));
  786. }
  787. $messages[] = $emptyLine = \sprintf('<error>%s</error>', str_repeat(' ', $len));
  788. if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  789. $messages[] = \sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::width($title))));
  790. }
  791. foreach ($lines as $line) {
  792. $messages[] = \sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
  793. }
  794. $messages[] = $emptyLine;
  795. $messages[] = '';
  796. $output->writeln($messages, OutputInterface::VERBOSITY_QUIET);
  797. if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  798. $output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
  799. // exception related properties
  800. $trace = $e->getTrace();
  801. array_unshift($trace, [
  802. 'function' => '',
  803. 'file' => $e->getFile() ?: 'n/a',
  804. 'line' => $e->getLine() ?: 'n/a',
  805. 'args' => [],
  806. ]);
  807. for ($i = 0, $count = \count($trace); $i < $count; ++$i) {
  808. $class = $trace[$i]['class'] ?? '';
  809. $type = $trace[$i]['type'] ?? '';
  810. $function = $trace[$i]['function'] ?? '';
  811. $file = $trace[$i]['file'] ?? 'n/a';
  812. $line = $trace[$i]['line'] ?? 'n/a';
  813. $output->writeln(\sprintf(' %s%s at <info>%s:%s</info>', $class, $function ? $type.$function.'()' : '', $file, $line), OutputInterface::VERBOSITY_QUIET);
  814. }
  815. $output->writeln('', OutputInterface::VERBOSITY_QUIET);
  816. }
  817. } while ($e = $e->getPrevious());
  818. }
  819. /**
  820. * Configures the input and output instances based on the user arguments and options.
  821. */
  822. protected function configureIO(InputInterface $input, OutputInterface $output): void
  823. {
  824. if ($input->hasParameterOption(['--ansi'], true)) {
  825. $output->setDecorated(true);
  826. } elseif ($input->hasParameterOption(['--no-ansi'], true)) {
  827. $output->setDecorated(false);
  828. }
  829. $shellVerbosity = match (true) {
  830. $input->hasParameterOption(['--silent'], true) => -2,
  831. $input->hasParameterOption(['--quiet', '-q'], true) => -1,
  832. $input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true) => 3,
  833. $input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true) => 2,
  834. $input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true) => 1,
  835. default => (int) ($_ENV['SHELL_VERBOSITY'] ?? $_SERVER['SHELL_VERBOSITY'] ?? getenv('SHELL_VERBOSITY')),
  836. };
  837. $output->setVerbosity(match ($shellVerbosity) {
  838. -2 => OutputInterface::VERBOSITY_SILENT,
  839. -1 => OutputInterface::VERBOSITY_QUIET,
  840. 1 => OutputInterface::VERBOSITY_VERBOSE,
  841. 2 => OutputInterface::VERBOSITY_VERY_VERBOSE,
  842. 3 => OutputInterface::VERBOSITY_DEBUG,
  843. default => ($shellVerbosity = 0) ?: $output->getVerbosity(),
  844. });
  845. if (0 > $shellVerbosity || $input->hasParameterOption(['--no-interaction', '-n'], true)) {
  846. $input->setInteractive(false);
  847. }
  848. if (\function_exists('putenv')) {
  849. @putenv('SHELL_VERBOSITY='.$shellVerbosity);
  850. }
  851. $_ENV['SHELL_VERBOSITY'] = $shellVerbosity;
  852. $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity;
  853. }
  854. /**
  855. * Runs the current command.
  856. *
  857. * If an event dispatcher has been attached to the application,
  858. * events are also dispatched during the life-cycle of the command.
  859. *
  860. * @return int 0 if everything went fine, or an error code
  861. */
  862. protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output): int
  863. {
  864. foreach ($command->getHelperSet() as $helper) {
  865. if ($helper instanceof InputAwareInterface) {
  866. $helper->setInput($input);
  867. }
  868. }
  869. $registeredSignals = false;
  870. if (($commandSignals = $command->getSubscribedSignals()) || $this->dispatcher && $this->signalsToDispatchEvent) {
  871. $signalRegistry = $this->getSignalRegistry();
  872. $registeredSignals = true;
  873. $this->getSignalRegistry()->pushCurrentHandlers();
  874. if ($this->dispatcher) {
  875. // We register application signals, so that we can dispatch the event
  876. foreach ($this->signalsToDispatchEvent as $signal) {
  877. $signalEvent = new ConsoleSignalEvent($command, $input, $output, $signal);
  878. $alarmEvent = \SIGALRM === $signal ? new ConsoleAlarmEvent($command, $input, $output) : null;
  879. $signalRegistry->register($signal, function ($signal) use ($signalEvent, $alarmEvent, $command, $commandSignals, $input, $output) {
  880. $this->dispatcher->dispatch($signalEvent, ConsoleEvents::SIGNAL);
  881. $exitCode = $signalEvent->getExitCode();
  882. if (null !== $alarmEvent) {
  883. if (false !== $exitCode) {
  884. $alarmEvent->setExitCode($exitCode);
  885. } else {
  886. $alarmEvent->abortExit();
  887. }
  888. $this->dispatcher->dispatch($alarmEvent);
  889. $exitCode = $alarmEvent->getExitCode();
  890. }
  891. // If the command is signalable, we call the handleSignal() method
  892. if (\in_array($signal, $commandSignals, true)) {
  893. $exitCode = $command->handleSignal($signal, $exitCode);
  894. }
  895. if (\SIGALRM === $signal) {
  896. $this->scheduleAlarm();
  897. }
  898. if (false !== $exitCode) {
  899. $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode, $signal);
  900. $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
  901. exit($event->getExitCode());
  902. }
  903. });
  904. }
  905. // then we register command signals, but not if already handled after the dispatcher
  906. $commandSignals = array_diff($commandSignals, $this->signalsToDispatchEvent);
  907. }
  908. foreach ($commandSignals as $signal) {
  909. $signalRegistry->register($signal, function (int $signal) use ($command): void {
  910. if (\SIGALRM === $signal) {
  911. $this->scheduleAlarm();
  912. }
  913. if (false !== $exitCode = $command->handleSignal($signal)) {
  914. exit($exitCode);
  915. }
  916. });
  917. }
  918. }
  919. if (null === $this->dispatcher) {
  920. try {
  921. return $command->run($input, $output);
  922. } finally {
  923. if ($registeredSignals) {
  924. $this->getSignalRegistry()->popPreviousHandlers();
  925. }
  926. }
  927. }
  928. // bind before the console.command event, so the listeners have access to input options/arguments
  929. try {
  930. $command->mergeApplicationDefinition();
  931. $input->bind($command->getDefinition());
  932. } catch (ExceptionInterface) {
  933. // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
  934. }
  935. $event = new ConsoleCommandEvent($command, $input, $output);
  936. $e = null;
  937. try {
  938. $this->dispatcher->dispatch($event, ConsoleEvents::COMMAND);
  939. if ($event->commandShouldRun()) {
  940. $exitCode = $command->run($input, $output);
  941. } else {
  942. $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
  943. }
  944. } catch (\Throwable $e) {
  945. $event = new ConsoleErrorEvent($input, $output, $e, $command);
  946. $this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
  947. $e = $event->getError();
  948. if (0 === $exitCode = $event->getExitCode()) {
  949. $e = null;
  950. }
  951. } finally {
  952. if ($registeredSignals) {
  953. $this->getSignalRegistry()->popPreviousHandlers();
  954. }
  955. }
  956. $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
  957. $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
  958. if (null !== $e) {
  959. throw $e;
  960. }
  961. return $event->getExitCode();
  962. }
  963. /**
  964. * Gets the name of the command based on input.
  965. */
  966. protected function getCommandName(InputInterface $input): ?string
  967. {
  968. return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument();
  969. }
  970. /**
  971. * Gets the default input definition.
  972. */
  973. protected function getDefaultInputDefinition(): InputDefinition
  974. {
  975. return new InputDefinition([
  976. new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
  977. 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'),
  978. new InputOption('--silent', null, InputOption::VALUE_NONE, 'Do not output any message'),
  979. new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Only errors are displayed. All other output is suppressed'),
  980. 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'),
  981. new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
  982. new InputOption('--ansi', '', InputOption::VALUE_NEGATABLE, 'Force (or disable --no-ansi) ANSI output', null),
  983. new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
  984. ]);
  985. }
  986. /**
  987. * Gets the default commands that should always be available.
  988. *
  989. * @return Command[]
  990. */
  991. protected function getDefaultCommands(): array
  992. {
  993. return [new HelpCommand(), new ListCommand(), new CompleteCommand(), new DumpCompletionCommand()];
  994. }
  995. /**
  996. * Gets the default helper set with the helpers that should always be available.
  997. */
  998. protected function getDefaultHelperSet(): HelperSet
  999. {
  1000. return new HelperSet([
  1001. new FormatterHelper(),
  1002. new DebugFormatterHelper(),
  1003. new ProcessHelper(),
  1004. new QuestionHelper(),
  1005. ]);
  1006. }
  1007. /**
  1008. * Returns abbreviated suggestions in string format.
  1009. */
  1010. private function getAbbreviationSuggestions(array $abbrevs): string
  1011. {
  1012. return ' '.implode("\n ", $abbrevs);
  1013. }
  1014. /**
  1015. * Returns the namespace part of the command name.
  1016. *
  1017. * This method is not part of public API and should not be used directly.
  1018. */
  1019. public function extractNamespace(string $name, ?int $limit = null): string
  1020. {
  1021. $parts = explode(':', $name, -1);
  1022. return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit));
  1023. }
  1024. /**
  1025. * Finds alternative of $name among $collection,
  1026. * if nothing is found in $collection, try in $abbrevs.
  1027. *
  1028. * @return string[]
  1029. */
  1030. private function findAlternatives(string $name, iterable $collection): array
  1031. {
  1032. $threshold = 1e3;
  1033. $alternatives = [];
  1034. $collectionParts = [];
  1035. foreach ($collection as $item) {
  1036. $collectionParts[$item] = explode(':', $item);
  1037. }
  1038. foreach (explode(':', $name) as $i => $subname) {
  1039. foreach ($collectionParts as $collectionName => $parts) {
  1040. $exists = isset($alternatives[$collectionName]);
  1041. if (!isset($parts[$i]) && $exists) {
  1042. $alternatives[$collectionName] += $threshold;
  1043. continue;
  1044. } elseif (!isset($parts[$i])) {
  1045. continue;
  1046. }
  1047. $lev = levenshtein($subname, $parts[$i]);
  1048. if ($lev <= \strlen($subname) / 3 || '' !== $subname && str_contains($parts[$i], $subname)) {
  1049. $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
  1050. } elseif ($exists) {
  1051. $alternatives[$collectionName] += $threshold;
  1052. }
  1053. }
  1054. }
  1055. foreach ($collection as $item) {
  1056. $lev = levenshtein($name, $item);
  1057. if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) {
  1058. $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
  1059. }
  1060. }
  1061. $alternatives = array_filter($alternatives, static fn ($lev) => $lev < 2 * $threshold);
  1062. ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE);
  1063. return array_keys($alternatives);
  1064. }
  1065. /**
  1066. * Sets the default Command name.
  1067. *
  1068. * @return $this
  1069. */
  1070. public function setDefaultCommand(string $commandName, bool $isSingleCommand = false): static
  1071. {
  1072. $this->defaultCommand = explode('|', ltrim($commandName, '|'))[0];
  1073. if ($isSingleCommand) {
  1074. // Ensure the command exist
  1075. $this->find($commandName);
  1076. $this->singleCommand = true;
  1077. }
  1078. return $this;
  1079. }
  1080. /**
  1081. * @internal
  1082. */
  1083. public function isSingleCommand(): bool
  1084. {
  1085. return $this->singleCommand;
  1086. }
  1087. private function splitStringByWidth(string $string, int $width): array
  1088. {
  1089. // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
  1090. // additionally, array_slice() is not enough as some character has doubled width.
  1091. // we need a function to split string not by character count but by string width
  1092. if (false === $encoding = mb_detect_encoding($string, null, true)) {
  1093. return str_split($string, $width);
  1094. }
  1095. $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
  1096. $lines = [];
  1097. $line = '';
  1098. $offset = 0;
  1099. while (preg_match('/.{1,10000}/u', $utf8String, $m, 0, $offset)) {
  1100. $offset += \strlen($m[0]);
  1101. foreach (preg_split('//u', $m[0]) as $char) {
  1102. // test if $char could be appended to current line
  1103. if (Helper::width($line.$char) <= $width) {
  1104. $line .= $char;
  1105. continue;
  1106. }
  1107. // if not, push current line to array and make new line
  1108. $lines[] = str_pad($line, $width);
  1109. $line = $char;
  1110. }
  1111. }
  1112. $lines[] = \count($lines) ? str_pad($line, $width) : $line;
  1113. return mb_convert_encoding($lines, $encoding, 'utf8');
  1114. }
  1115. /**
  1116. * Returns all namespaces of the command name.
  1117. *
  1118. * @return string[]
  1119. */
  1120. private function extractAllNamespaces(string $name): array
  1121. {
  1122. // -1 as third argument is needed to skip the command short name when exploding
  1123. $parts = explode(':', $name, -1);
  1124. $namespaces = [];
  1125. foreach ($parts as $part) {
  1126. if (\count($namespaces)) {
  1127. $namespaces[] = end($namespaces).':'.$part;
  1128. } else {
  1129. $namespaces[] = $part;
  1130. }
  1131. }
  1132. return $namespaces;
  1133. }
  1134. private function init(): void
  1135. {
  1136. if ($this->initialized) {
  1137. return;
  1138. }
  1139. $this->initialized = true;
  1140. if ((new \ReflectionMethod($this, 'add'))->getDeclaringClass()->getName() !== (new \ReflectionMethod($this, 'addCommand'))->getDeclaringClass()->getName()) {
  1141. $adder = $this->add(...);
  1142. } else {
  1143. $adder = $this->addCommand(...);
  1144. }
  1145. foreach ($this->getDefaultCommands() as $command) {
  1146. $adder($command);
  1147. }
  1148. }
  1149. }