Application.php 44 KB

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