Application.php 39 KB

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