Application.php 43 KB

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