Application.php 38 KB

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