Application.php 37 KB

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