Application.php 42 KB

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