Application.php 43 KB

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