Application.php 40 KB

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