PageRenderTime 54ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

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

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