PageRenderTime 78ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/src/Symfony/Component/Console/Application.php

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