Application.php 44 KB

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