Application.php 40 KB

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