Application.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348
  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. if (\count($commands) > 1) {
  660. $usableWidth = $this->terminal->getWidth() - 10;
  661. $abbrevs = array_values($commands);
  662. $maxLen = 0;
  663. foreach ($abbrevs as $abbrev) {
  664. $maxLen = max(Helper::width($abbrev), $maxLen);
  665. }
  666. $abbrevs = array_map(function ($cmd) use ($commandList, $usableWidth, $maxLen, &$commands) {
  667. if ($commandList[$cmd]->isHidden()) {
  668. unset($commands[array_search($cmd, $commands)]);
  669. return false;
  670. }
  671. $abbrev = str_pad($cmd, $maxLen, ' ').' '.$commandList[$cmd]->getDescription();
  672. return Helper::width($abbrev) > $usableWidth ? Helper::substr($abbrev, 0, $usableWidth - 3).'...' : $abbrev;
  673. }, array_values($commands));
  674. if (\count($commands) > 1) {
  675. $suggestions = $this->getAbbreviationSuggestions(array_filter($abbrevs));
  676. throw new CommandNotFoundException(\sprintf("Command \"%s\" is ambiguous.\nDid you mean one of these?\n%s.", $name, $suggestions), array_values($commands));
  677. }
  678. }
  679. $command = $commands ? $this->get(reset($commands)) : null;
  680. if (!$command || $command->isHidden()) {
  681. throw new CommandNotFoundException(\sprintf('The command "%s" does not exist.', $name));
  682. }
  683. return $command;
  684. }
  685. /**
  686. * Gets the commands (registered in the given namespace if provided).
  687. *
  688. * The array keys are the full names and the values the command instances.
  689. *
  690. * @return Command[]
  691. */
  692. public function all(?string $namespace = null): array
  693. {
  694. $this->init();
  695. if (null === $namespace) {
  696. if (!$this->commandLoader) {
  697. return $this->commands;
  698. }
  699. $commands = $this->commands;
  700. foreach ($this->commandLoader->getNames() as $name) {
  701. if (!isset($commands[$name]) && $this->has($name)) {
  702. $commands[$name] = $this->get($name);
  703. }
  704. }
  705. return $commands;
  706. }
  707. $commands = [];
  708. foreach ($this->commands as $name => $command) {
  709. if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
  710. $commands[$name] = $command;
  711. }
  712. }
  713. if ($this->commandLoader) {
  714. foreach ($this->commandLoader->getNames() as $name) {
  715. if (!isset($commands[$name]) && $namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1) && $this->has($name)) {
  716. $commands[$name] = $this->get($name);
  717. }
  718. }
  719. }
  720. return $commands;
  721. }
  722. /**
  723. * Returns an array of possible abbreviations given a set of names.
  724. *
  725. * @return string[][]
  726. */
  727. public static function getAbbreviations(array $names): array
  728. {
  729. $abbrevs = [];
  730. foreach ($names as $name) {
  731. for ($len = \strlen($name); $len > 0; --$len) {
  732. $abbrev = substr($name, 0, $len);
  733. $abbrevs[$abbrev][] = $name;
  734. }
  735. }
  736. return $abbrevs;
  737. }
  738. public function renderThrowable(\Throwable $e, OutputInterface $output): void
  739. {
  740. $output->writeln('', OutputInterface::VERBOSITY_QUIET);
  741. $this->doRenderThrowable($e, $output);
  742. if (null !== $this->runningCommand) {
  743. $output->writeln(\sprintf('<info>%s</info>', OutputFormatter::escape(\sprintf($this->runningCommand->getSynopsis(), $this->getName()))), OutputInterface::VERBOSITY_QUIET);
  744. $output->writeln('', OutputInterface::VERBOSITY_QUIET);
  745. }
  746. }
  747. protected function doRenderThrowable(\Throwable $e, OutputInterface $output): void
  748. {
  749. do {
  750. $message = trim($e->getMessage());
  751. if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  752. $class = get_debug_type($e);
  753. $title = \sprintf(' [%s%s] ', $class, 0 !== ($code = $e->getCode()) ? ' ('.$code.')' : '');
  754. $len = Helper::width($title);
  755. } else {
  756. $len = 0;
  757. }
  758. if (str_contains($message, "@anonymous\0")) {
  759. $message = preg_replace_callback('/[a-zA-Z_\x7f-\xff][\\\\a-zA-Z0-9_\x7f-\xff]*+@anonymous\x00.*?\.php(?:0x?|:[0-9]++\$)?[0-9a-fA-F]++/', fn ($m) => class_exists($m[0], false) ? (get_parent_class($m[0]) ?: key(class_implements($m[0])) ?: 'class').'@anonymous' : $m[0], $message);
  760. }
  761. $width = $this->terminal->getWidth() ? $this->terminal->getWidth() - 1 : \PHP_INT_MAX;
  762. $lines = [];
  763. foreach ('' !== $message ? preg_split('/\r?\n/', $message) : [] as $line) {
  764. foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
  765. // pre-format lines to get the right string length
  766. $lineLength = Helper::width($line) + 4;
  767. $lines[] = [$line, $lineLength];
  768. $len = max($lineLength, $len);
  769. }
  770. }
  771. $messages = [];
  772. if (!$e instanceof ExceptionInterface || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  773. $messages[] = \sprintf('<comment>%s</comment>', OutputFormatter::escape(\sprintf('In %s line %s:', basename($e->getFile()) ?: 'n/a', $e->getLine() ?: 'n/a')));
  774. }
  775. $messages[] = $emptyLine = \sprintf('<error>%s</error>', str_repeat(' ', $len));
  776. if ('' === $message || OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  777. $messages[] = \sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - Helper::width($title))));
  778. }
  779. foreach ($lines as $line) {
  780. $messages[] = \sprintf('<error> %s %s</error>', OutputFormatter::escape($line[0]), str_repeat(' ', $len - $line[1]));
  781. }
  782. $messages[] = $emptyLine;
  783. $messages[] = '';
  784. $output->writeln($messages, OutputInterface::VERBOSITY_QUIET);
  785. if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  786. $output->writeln('<comment>Exception trace:</comment>', OutputInterface::VERBOSITY_QUIET);
  787. // exception related properties
  788. $trace = $e->getTrace();
  789. array_unshift($trace, [
  790. 'function' => '',
  791. 'file' => $e->getFile() ?: 'n/a',
  792. 'line' => $e->getLine() ?: 'n/a',
  793. 'args' => [],
  794. ]);
  795. for ($i = 0, $count = \count($trace); $i < $count; ++$i) {
  796. $class = $trace[$i]['class'] ?? '';
  797. $type = $trace[$i]['type'] ?? '';
  798. $function = $trace[$i]['function'] ?? '';
  799. $file = $trace[$i]['file'] ?? 'n/a';
  800. $line = $trace[$i]['line'] ?? 'n/a';
  801. $output->writeln(\sprintf(' %s%s at <info>%s:%s</info>', $class, $function ? $type.$function.'()' : '', $file, $line), OutputInterface::VERBOSITY_QUIET);
  802. }
  803. $output->writeln('', OutputInterface::VERBOSITY_QUIET);
  804. }
  805. } while ($e = $e->getPrevious());
  806. }
  807. /**
  808. * Configures the input and output instances based on the user arguments and options.
  809. */
  810. protected function configureIO(InputInterface $input, OutputInterface $output): void
  811. {
  812. if ($input->hasParameterOption(['--ansi'], true)) {
  813. $output->setDecorated(true);
  814. } elseif ($input->hasParameterOption(['--no-ansi'], true)) {
  815. $output->setDecorated(false);
  816. }
  817. $shellVerbosity = match (true) {
  818. $input->hasParameterOption(['--silent'], true) => -2,
  819. $input->hasParameterOption(['--quiet', '-q'], true) => -1,
  820. $input->hasParameterOption('-vvv', true) || $input->hasParameterOption('--verbose=3', true) || 3 === $input->getParameterOption('--verbose', false, true) => 3,
  821. $input->hasParameterOption('-vv', true) || $input->hasParameterOption('--verbose=2', true) || 2 === $input->getParameterOption('--verbose', false, true) => 2,
  822. $input->hasParameterOption('-v', true) || $input->hasParameterOption('--verbose=1', true) || $input->hasParameterOption('--verbose', true) || $input->getParameterOption('--verbose', false, true) => 1,
  823. default => (int) ($_ENV['SHELL_VERBOSITY'] ?? $_SERVER['SHELL_VERBOSITY'] ?? getenv('SHELL_VERBOSITY')),
  824. };
  825. $output->setVerbosity(match ($shellVerbosity) {
  826. -2 => OutputInterface::VERBOSITY_SILENT,
  827. -1 => OutputInterface::VERBOSITY_QUIET,
  828. 1 => OutputInterface::VERBOSITY_VERBOSE,
  829. 2 => OutputInterface::VERBOSITY_VERY_VERBOSE,
  830. 3 => OutputInterface::VERBOSITY_DEBUG,
  831. default => ($shellVerbosity = 0) ?: $output->getVerbosity(),
  832. });
  833. if (0 > $shellVerbosity || $input->hasParameterOption(['--no-interaction', '-n'], true)) {
  834. $input->setInteractive(false);
  835. }
  836. if (\function_exists('putenv')) {
  837. @putenv('SHELL_VERBOSITY='.$shellVerbosity);
  838. }
  839. $_ENV['SHELL_VERBOSITY'] = $shellVerbosity;
  840. $_SERVER['SHELL_VERBOSITY'] = $shellVerbosity;
  841. }
  842. /**
  843. * Runs the current command.
  844. *
  845. * If an event dispatcher has been attached to the application,
  846. * events are also dispatched during the life-cycle of the command.
  847. *
  848. * @return int 0 if everything went fine, or an error code
  849. */
  850. protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output): int
  851. {
  852. foreach ($command->getHelperSet() as $helper) {
  853. if ($helper instanceof InputAwareInterface) {
  854. $helper->setInput($input);
  855. }
  856. }
  857. $registeredSignals = false;
  858. if (($commandSignals = $command->getSubscribedSignals()) || $this->dispatcher && $this->signalsToDispatchEvent) {
  859. $signalRegistry = $this->getSignalRegistry();
  860. $registeredSignals = true;
  861. $this->getSignalRegistry()->pushCurrentHandlers();
  862. if ($this->dispatcher) {
  863. // We register application signals, so that we can dispatch the event
  864. foreach ($this->signalsToDispatchEvent as $signal) {
  865. $signalEvent = new ConsoleSignalEvent($command, $input, $output, $signal);
  866. $alarmEvent = \SIGALRM === $signal ? new ConsoleAlarmEvent($command, $input, $output) : null;
  867. $signalRegistry->register($signal, function ($signal) use ($signalEvent, $alarmEvent, $command, $commandSignals, $input, $output) {
  868. $this->dispatcher->dispatch($signalEvent, ConsoleEvents::SIGNAL);
  869. $exitCode = $signalEvent->getExitCode();
  870. if (null !== $alarmEvent) {
  871. if (false !== $exitCode) {
  872. $alarmEvent->setExitCode($exitCode);
  873. } else {
  874. $alarmEvent->abortExit();
  875. }
  876. $this->dispatcher->dispatch($alarmEvent);
  877. $exitCode = $alarmEvent->getExitCode();
  878. }
  879. // If the command is signalable, we call the handleSignal() method
  880. if (\in_array($signal, $commandSignals, true)) {
  881. $exitCode = $command->handleSignal($signal, $exitCode);
  882. }
  883. if (\SIGALRM === $signal) {
  884. $this->scheduleAlarm();
  885. }
  886. if (false !== $exitCode) {
  887. $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode, $signal);
  888. $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
  889. exit($event->getExitCode());
  890. }
  891. });
  892. }
  893. // then we register command signals, but not if already handled after the dispatcher
  894. $commandSignals = array_diff($commandSignals, $this->signalsToDispatchEvent);
  895. }
  896. foreach ($commandSignals as $signal) {
  897. $signalRegistry->register($signal, function (int $signal) use ($command): void {
  898. if (\SIGALRM === $signal) {
  899. $this->scheduleAlarm();
  900. }
  901. if (false !== $exitCode = $command->handleSignal($signal)) {
  902. exit($exitCode);
  903. }
  904. });
  905. }
  906. }
  907. if (null === $this->dispatcher) {
  908. try {
  909. return $command->run($input, $output);
  910. } finally {
  911. if ($registeredSignals) {
  912. $this->getSignalRegistry()->popPreviousHandlers();
  913. }
  914. }
  915. }
  916. // bind before the console.command event, so the listeners have access to input options/arguments
  917. try {
  918. $command->mergeApplicationDefinition();
  919. $input->bind($command->getDefinition());
  920. } catch (ExceptionInterface) {
  921. // ignore invalid options/arguments for now, to allow the event listeners to customize the InputDefinition
  922. }
  923. $event = new ConsoleCommandEvent($command, $input, $output);
  924. $e = null;
  925. try {
  926. $this->dispatcher->dispatch($event, ConsoleEvents::COMMAND);
  927. if ($event->commandShouldRun()) {
  928. $exitCode = $command->run($input, $output);
  929. } else {
  930. $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
  931. }
  932. } catch (\Throwable $e) {
  933. $event = new ConsoleErrorEvent($input, $output, $e, $command);
  934. $this->dispatcher->dispatch($event, ConsoleEvents::ERROR);
  935. $e = $event->getError();
  936. if (0 === $exitCode = $event->getExitCode()) {
  937. $e = null;
  938. }
  939. } finally {
  940. if ($registeredSignals) {
  941. $this->getSignalRegistry()->popPreviousHandlers();
  942. }
  943. }
  944. $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
  945. $this->dispatcher->dispatch($event, ConsoleEvents::TERMINATE);
  946. if (null !== $e) {
  947. throw $e;
  948. }
  949. return $event->getExitCode();
  950. }
  951. /**
  952. * Gets the name of the command based on input.
  953. */
  954. protected function getCommandName(InputInterface $input): ?string
  955. {
  956. return $this->singleCommand ? $this->defaultCommand : $input->getFirstArgument();
  957. }
  958. /**
  959. * Gets the default input definition.
  960. */
  961. protected function getDefaultInputDefinition(): InputDefinition
  962. {
  963. return new InputDefinition([
  964. new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
  965. 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'),
  966. new InputOption('--silent', null, InputOption::VALUE_NONE, 'Do not output any message'),
  967. new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Only errors are displayed. All other output is suppressed'),
  968. 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'),
  969. new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
  970. new InputOption('--ansi', '', InputOption::VALUE_NEGATABLE, 'Force (or disable --no-ansi) ANSI output', null),
  971. new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
  972. ]);
  973. }
  974. /**
  975. * Gets the default commands that should always be available.
  976. *
  977. * @return Command[]
  978. */
  979. protected function getDefaultCommands(): array
  980. {
  981. return [new HelpCommand(), new ListCommand(), new CompleteCommand(), new DumpCompletionCommand()];
  982. }
  983. /**
  984. * Gets the default helper set with the helpers that should always be available.
  985. */
  986. protected function getDefaultHelperSet(): HelperSet
  987. {
  988. return new HelperSet([
  989. new FormatterHelper(),
  990. new DebugFormatterHelper(),
  991. new ProcessHelper(),
  992. new QuestionHelper(),
  993. ]);
  994. }
  995. /**
  996. * Returns abbreviated suggestions in string format.
  997. */
  998. private function getAbbreviationSuggestions(array $abbrevs): string
  999. {
  1000. return ' '.implode("\n ", $abbrevs);
  1001. }
  1002. /**
  1003. * Returns the namespace part of the command name.
  1004. *
  1005. * This method is not part of public API and should not be used directly.
  1006. */
  1007. public function extractNamespace(string $name, ?int $limit = null): string
  1008. {
  1009. $parts = explode(':', $name, -1);
  1010. return implode(':', null === $limit ? $parts : \array_slice($parts, 0, $limit));
  1011. }
  1012. /**
  1013. * Finds alternative of $name among $collection,
  1014. * if nothing is found in $collection, try in $abbrevs.
  1015. *
  1016. * @return string[]
  1017. */
  1018. private function findAlternatives(string $name, iterable $collection): array
  1019. {
  1020. $threshold = 1e3;
  1021. $alternatives = [];
  1022. $collectionParts = [];
  1023. foreach ($collection as $item) {
  1024. $collectionParts[$item] = explode(':', $item);
  1025. }
  1026. foreach (explode(':', $name) as $i => $subname) {
  1027. foreach ($collectionParts as $collectionName => $parts) {
  1028. $exists = isset($alternatives[$collectionName]);
  1029. if (!isset($parts[$i]) && $exists) {
  1030. $alternatives[$collectionName] += $threshold;
  1031. continue;
  1032. } elseif (!isset($parts[$i])) {
  1033. continue;
  1034. }
  1035. $lev = levenshtein($subname, $parts[$i]);
  1036. if ($lev <= \strlen($subname) / 3 || '' !== $subname && str_contains($parts[$i], $subname)) {
  1037. $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
  1038. } elseif ($exists) {
  1039. $alternatives[$collectionName] += $threshold;
  1040. }
  1041. }
  1042. }
  1043. foreach ($collection as $item) {
  1044. $lev = levenshtein($name, $item);
  1045. if ($lev <= \strlen($name) / 3 || str_contains($item, $name)) {
  1046. $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
  1047. }
  1048. }
  1049. $alternatives = array_filter($alternatives, fn ($lev) => $lev < 2 * $threshold);
  1050. ksort($alternatives, \SORT_NATURAL | \SORT_FLAG_CASE);
  1051. return array_keys($alternatives);
  1052. }
  1053. /**
  1054. * Sets the default Command name.
  1055. *
  1056. * @return $this
  1057. */
  1058. public function setDefaultCommand(string $commandName, bool $isSingleCommand = false): static
  1059. {
  1060. $this->defaultCommand = explode('|', ltrim($commandName, '|'))[0];
  1061. if ($isSingleCommand) {
  1062. // Ensure the command exist
  1063. $this->find($commandName);
  1064. $this->singleCommand = true;
  1065. }
  1066. return $this;
  1067. }
  1068. /**
  1069. * @internal
  1070. */
  1071. public function isSingleCommand(): bool
  1072. {
  1073. return $this->singleCommand;
  1074. }
  1075. private function splitStringByWidth(string $string, int $width): array
  1076. {
  1077. // str_split is not suitable for multi-byte characters, we should use preg_split to get char array properly.
  1078. // additionally, array_slice() is not enough as some character has doubled width.
  1079. // we need a function to split string not by character count but by string width
  1080. if (false === $encoding = mb_detect_encoding($string, null, true)) {
  1081. return str_split($string, $width);
  1082. }
  1083. $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
  1084. $lines = [];
  1085. $line = '';
  1086. $offset = 0;
  1087. while (preg_match('/.{1,10000}/u', $utf8String, $m, 0, $offset)) {
  1088. $offset += \strlen($m[0]);
  1089. foreach (preg_split('//u', $m[0]) as $char) {
  1090. // test if $char could be appended to current line
  1091. if (Helper::width($line.$char) <= $width) {
  1092. $line .= $char;
  1093. continue;
  1094. }
  1095. // if not, push current line to array and make new line
  1096. $lines[] = str_pad($line, $width);
  1097. $line = $char;
  1098. }
  1099. }
  1100. $lines[] = \count($lines) ? str_pad($line, $width) : $line;
  1101. mb_convert_variables($encoding, 'utf8', $lines);
  1102. return $lines;
  1103. }
  1104. /**
  1105. * Returns all namespaces of the command name.
  1106. *
  1107. * @return string[]
  1108. */
  1109. private function extractAllNamespaces(string $name): array
  1110. {
  1111. // -1 as third argument is needed to skip the command short name when exploding
  1112. $parts = explode(':', $name, -1);
  1113. $namespaces = [];
  1114. foreach ($parts as $part) {
  1115. if (\count($namespaces)) {
  1116. $namespaces[] = end($namespaces).':'.$part;
  1117. } else {
  1118. $namespaces[] = $part;
  1119. }
  1120. }
  1121. return $namespaces;
  1122. }
  1123. private function init(): void
  1124. {
  1125. if ($this->initialized) {
  1126. return;
  1127. }
  1128. $this->initialized = true;
  1129. if ((new \ReflectionMethod($this, 'add'))->getDeclaringClass()->getName() !== (new \ReflectionMethod($this, 'addCommand'))->getDeclaringClass()->getName()) {
  1130. $adder = $this->add(...);
  1131. } else {
  1132. $adder = $this->addCommand(...);
  1133. }
  1134. foreach ($this->getDefaultCommands() as $command) {
  1135. $adder($command);
  1136. }
  1137. }
  1138. }