You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1239 lines
42 KiB

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