No Description

Application.php 44KB

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