Application.php 44 KB

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