Application.php 39 KB

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