Application.php 36 KB

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