Application.php 40 KB

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