PageRenderTime 61ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

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

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