Application.php 43 KB

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