Application.php 45 KB

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