Application.php 39KB

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