PageRenderTime 60ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

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

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