Application.php 42 KB

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