Application.php 42 KB

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