Application.php 44 KB

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