Application.php 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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\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 = new HelperSet(array(
  70. new FormatterHelper(),
  71. new DialogHelper(),
  72. ));
  73. $this->add(new HelpCommand());
  74. $this->add(new ListCommand());
  75. $this->definition = new InputDefinition(array(
  76. new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
  77. new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
  78. new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message.'),
  79. new InputOption('--verbose', '-v', InputOption::VALUE_NONE, 'Increase verbosity of messages.'),
  80. new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version.'),
  81. new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output.'),
  82. new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output.'),
  83. new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question.'),
  84. ));
  85. }
  86. /**
  87. * Runs the current application.
  88. *
  89. * @param InputInterface $input An Input instance
  90. * @param OutputInterface $output An Output instance
  91. *
  92. * @return integer 0 if everything went fine, or an error code
  93. *
  94. * @throws \Exception When doRun returns Exception
  95. *
  96. * @api
  97. */
  98. public function run(InputInterface $input = null, OutputInterface $output = null)
  99. {
  100. if (null === $input) {
  101. $input = new ArgvInput();
  102. }
  103. if (null === $output) {
  104. $output = new ConsoleOutput();
  105. }
  106. try {
  107. $statusCode = $this->doRun($input, $output);
  108. } catch (\Exception $e) {
  109. if (!$this->catchExceptions) {
  110. throw $e;
  111. }
  112. $this->renderException($e, $output);
  113. $statusCode = $e->getCode();
  114. $statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1;
  115. }
  116. if ($this->autoExit) {
  117. if ($statusCode > 255) {
  118. $statusCode = 255;
  119. }
  120. // @codeCoverageIgnoreStart
  121. exit($statusCode);
  122. // @codeCoverageIgnoreEnd
  123. }
  124. return $statusCode;
  125. }
  126. /**
  127. * Runs the current application.
  128. *
  129. * @param InputInterface $input An Input instance
  130. * @param OutputInterface $output An Output instance
  131. *
  132. * @return integer 0 if everything went fine, or an error code
  133. */
  134. public function doRun(InputInterface $input, OutputInterface $output)
  135. {
  136. $name = $this->getCommandName($input);
  137. if (true === $input->hasParameterOption(array('--ansi'))) {
  138. $output->setDecorated(true);
  139. } elseif (true === $input->hasParameterOption(array('--no-ansi'))) {
  140. $output->setDecorated(false);
  141. }
  142. if (true === $input->hasParameterOption(array('--help', '-h'))) {
  143. if (!$name) {
  144. $name = 'help';
  145. $input = new ArrayInput(array('command' => 'help'));
  146. } else {
  147. $this->wantHelps = true;
  148. }
  149. }
  150. if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
  151. $input->setInteractive(false);
  152. }
  153. if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
  154. $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
  155. } elseif (true === $input->hasParameterOption(array('--verbose', '-v'))) {
  156. $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
  157. }
  158. if (true === $input->hasParameterOption(array('--version', '-V'))) {
  159. $output->writeln($this->getLongVersion());
  160. return 0;
  161. }
  162. if (!$name) {
  163. $name = 'list';
  164. $input = new ArrayInput(array('command' => 'list'));
  165. }
  166. // the command name MUST be the first element of the input
  167. $command = $this->find($name);
  168. $this->runningCommand = $command;
  169. $statusCode = $command->run($input, $output);
  170. $this->runningCommand = null;
  171. return is_numeric($statusCode) ? $statusCode : 0;
  172. }
  173. /**
  174. * Set a helper set to be used with the command.
  175. *
  176. * @param HelperSet $helperSet The helper set
  177. *
  178. * @api
  179. */
  180. public function setHelperSet(HelperSet $helperSet)
  181. {
  182. $this->helperSet = $helperSet;
  183. }
  184. /**
  185. * Get the helper set associated with the command.
  186. *
  187. * @return HelperSet The HelperSet instance associated with this command
  188. *
  189. * @api
  190. */
  191. public function getHelperSet()
  192. {
  193. return $this->helperSet;
  194. }
  195. /**
  196. * Gets the InputDefinition related to this Application.
  197. *
  198. * @return InputDefinition The InputDefinition instance
  199. */
  200. public function getDefinition()
  201. {
  202. return $this->definition;
  203. }
  204. /**
  205. * Gets the help message.
  206. *
  207. * @return string A help message.
  208. */
  209. public function getHelp()
  210. {
  211. $messages = array(
  212. $this->getLongVersion(),
  213. '',
  214. '<comment>Usage:</comment>',
  215. sprintf(" [options] command [arguments]\n"),
  216. '<comment>Options:</comment>',
  217. );
  218. foreach ($this->getDefinition()->getOptions() as $option) {
  219. $messages[] = sprintf(' %-29s %s %s',
  220. '<info>--'.$option->getName().'</info>',
  221. $option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : ' ',
  222. $option->getDescription()
  223. );
  224. }
  225. return implode("\n", $messages);
  226. }
  227. /**
  228. * Sets whether to catch exceptions or not during commands execution.
  229. *
  230. * @param Boolean $boolean Whether to catch exceptions or not during commands execution
  231. *
  232. * @api
  233. */
  234. public function setCatchExceptions($boolean)
  235. {
  236. $this->catchExceptions = (Boolean) $boolean;
  237. }
  238. /**
  239. * Sets whether to automatically exit after a command execution or not.
  240. *
  241. * @param Boolean $boolean Whether to automatically exit after a command execution or not
  242. *
  243. * @api
  244. */
  245. public function setAutoExit($boolean)
  246. {
  247. $this->autoExit = (Boolean) $boolean;
  248. }
  249. /**
  250. * Gets the name of the application.
  251. *
  252. * @return string The application name
  253. *
  254. * @api
  255. */
  256. public function getName()
  257. {
  258. return $this->name;
  259. }
  260. /**
  261. * Sets the application name.
  262. *
  263. * @param string $name The application name
  264. *
  265. * @api
  266. */
  267. public function setName($name)
  268. {
  269. $this->name = $name;
  270. }
  271. /**
  272. * Gets the application version.
  273. *
  274. * @return string The application version
  275. *
  276. * @api
  277. */
  278. public function getVersion()
  279. {
  280. return $this->version;
  281. }
  282. /**
  283. * Sets the application version.
  284. *
  285. * @param string $version The application version
  286. *
  287. * @api
  288. */
  289. public function setVersion($version)
  290. {
  291. $this->version = $version;
  292. }
  293. /**
  294. * Returns the long version of the application.
  295. *
  296. * @return string The long application version
  297. *
  298. * @api
  299. */
  300. public function getLongVersion()
  301. {
  302. if ('UNKNOWN' !== $this->getName() && 'UNKNOWN' !== $this->getVersion()) {
  303. return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
  304. }
  305. return '<info>Console Tool</info>';
  306. }
  307. /**
  308. * Registers a new command.
  309. *
  310. * @param string $name The command name
  311. *
  312. * @return Command The newly created command
  313. *
  314. * @api
  315. */
  316. public function register($name)
  317. {
  318. return $this->add(new Command($name));
  319. }
  320. /**
  321. * Adds an array of command objects.
  322. *
  323. * @param Command[] $commands An array of commands
  324. *
  325. * @api
  326. */
  327. public function addCommands(array $commands)
  328. {
  329. foreach ($commands as $command) {
  330. $this->add($command);
  331. }
  332. }
  333. /**
  334. * Adds a command object.
  335. *
  336. * If a command with the same name already exists, it will be overridden.
  337. *
  338. * @param Command $command A Command object
  339. *
  340. * @return Command The registered command
  341. *
  342. * @api
  343. */
  344. public function add(Command $command)
  345. {
  346. $command->setApplication($this);
  347. $this->commands[$command->getName()] = $command;
  348. foreach ($command->getAliases() as $alias) {
  349. $this->commands[$alias] = $command;
  350. }
  351. return $command;
  352. }
  353. /**
  354. * Returns a registered command by name or alias.
  355. *
  356. * @param string $name The command name or alias
  357. *
  358. * @return Command A Command object
  359. *
  360. * @throws \InvalidArgumentException When command name given does not exist
  361. *
  362. * @api
  363. */
  364. public function get($name)
  365. {
  366. if (!isset($this->commands[$name])) {
  367. throw new \InvalidArgumentException(sprintf('The command "%s" does not exist.', $name));
  368. }
  369. $command = $this->commands[$name];
  370. if ($this->wantHelps) {
  371. $this->wantHelps = false;
  372. $helpCommand = $this->get('help');
  373. $helpCommand->setCommand($command);
  374. return $helpCommand;
  375. }
  376. return $command;
  377. }
  378. /**
  379. * Returns true if the command exists, false otherwise.
  380. *
  381. * @param string $name The command name or alias
  382. *
  383. * @return Boolean true if the command exists, false otherwise
  384. *
  385. * @api
  386. */
  387. public function has($name)
  388. {
  389. return isset($this->commands[$name]);
  390. }
  391. /**
  392. * Returns an array of all unique namespaces used by currently registered commands.
  393. *
  394. * It does not returns the global namespace which always exists.
  395. *
  396. * @return array An array of namespaces
  397. */
  398. public function getNamespaces()
  399. {
  400. $namespaces = array();
  401. foreach ($this->commands as $command) {
  402. $namespaces[] = $this->extractNamespace($command->getName());
  403. foreach ($command->getAliases() as $alias) {
  404. $namespaces[] = $this->extractNamespace($alias);
  405. }
  406. }
  407. return array_values(array_unique(array_filter($namespaces)));
  408. }
  409. /**
  410. * Finds a registered namespace by a name or an abbreviation.
  411. *
  412. * @param string $namespace A namespace or abbreviation to search for
  413. *
  414. * @return string A registered namespace
  415. *
  416. * @throws \InvalidArgumentException When namespace is incorrect or ambiguous
  417. */
  418. public function findNamespace($namespace)
  419. {
  420. $allNamespaces = array();
  421. foreach ($this->getNamespaces() as $n) {
  422. $allNamespaces[$n] = explode(':', $n);
  423. }
  424. $found = array();
  425. foreach (explode(':', $namespace) as $i => $part) {
  426. $abbrevs = static::getAbbreviations(array_unique(array_values(array_filter(array_map(function ($p) use ($i) { return isset($p[$i]) ? $p[$i] : ''; }, $allNamespaces)))));
  427. if (!isset($abbrevs[$part])) {
  428. throw new \InvalidArgumentException(sprintf('There are no commands defined in the "%s" namespace.', $namespace));
  429. }
  430. if (count($abbrevs[$part]) > 1) {
  431. throw new \InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions($abbrevs[$part])));
  432. }
  433. $found[] = $abbrevs[$part][0];
  434. }
  435. return implode(':', $found);
  436. }
  437. /**
  438. * Finds a command by name or alias.
  439. *
  440. * Contrary to get, this command tries to find the best
  441. * match if you give it an abbreviation of a name or alias.
  442. *
  443. * @param string $name A command name or a command alias
  444. *
  445. * @return Command A Command instance
  446. *
  447. * @throws \InvalidArgumentException When command name is incorrect or ambiguous
  448. *
  449. * @api
  450. */
  451. public function find($name)
  452. {
  453. // namespace
  454. $namespace = '';
  455. $searchName = $name;
  456. if (false !== $pos = strrpos($name, ':')) {
  457. $namespace = $this->findNamespace(substr($name, 0, $pos));
  458. $searchName = $namespace.substr($name, $pos);
  459. }
  460. // name
  461. $commands = array();
  462. foreach ($this->commands as $command) {
  463. if ($this->extractNamespace($command->getName()) == $namespace) {
  464. $commands[] = $command->getName();
  465. }
  466. }
  467. $abbrevs = static::getAbbreviations(array_unique($commands));
  468. if (isset($abbrevs[$searchName]) && 1 == count($abbrevs[$searchName])) {
  469. return $this->get($abbrevs[$searchName][0]);
  470. }
  471. if (isset($abbrevs[$searchName]) && count($abbrevs[$searchName]) > 1) {
  472. $suggestions = $this->getAbbreviationSuggestions($abbrevs[$searchName]);
  473. throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions));
  474. }
  475. // aliases
  476. $aliases = array();
  477. foreach ($this->commands as $command) {
  478. foreach ($command->getAliases() as $alias) {
  479. if ($this->extractNamespace($alias) == $namespace) {
  480. $aliases[] = $alias;
  481. }
  482. }
  483. }
  484. $abbrevs = static::getAbbreviations(array_unique($aliases));
  485. if (!isset($abbrevs[$searchName])) {
  486. throw new \InvalidArgumentException(sprintf('Command "%s" is not defined.', $name));
  487. }
  488. if (count($abbrevs[$searchName]) > 1) {
  489. throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $this->getAbbreviationSuggestions($abbrevs[$searchName])));
  490. }
  491. return $this->get($abbrevs[$searchName][0]);
  492. }
  493. /**
  494. * Gets the commands (registered in the given namespace if provided).
  495. *
  496. * The array keys are the full names and the values the command instances.
  497. *
  498. * @param string $namespace A namespace name
  499. *
  500. * @return array An array of Command instances
  501. *
  502. * @api
  503. */
  504. public function all($namespace = null)
  505. {
  506. if (null === $namespace) {
  507. return $this->commands;
  508. }
  509. $commands = array();
  510. foreach ($this->commands as $name => $command) {
  511. if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
  512. $commands[$name] = $command;
  513. }
  514. }
  515. return $commands;
  516. }
  517. /**
  518. * Returns an array of possible abbreviations given a set of names.
  519. *
  520. * @param array $names An array of names
  521. *
  522. * @return array An array of abbreviations
  523. */
  524. static public function getAbbreviations($names)
  525. {
  526. $abbrevs = array();
  527. foreach ($names as $name) {
  528. for ($len = strlen($name) - 1; $len > 0; --$len) {
  529. $abbrev = substr($name, 0, $len);
  530. if (!isset($abbrevs[$abbrev])) {
  531. $abbrevs[$abbrev] = array($name);
  532. } else {
  533. $abbrevs[$abbrev][] = $name;
  534. }
  535. }
  536. }
  537. // Non-abbreviations always get entered, even if they aren't unique
  538. foreach ($names as $name) {
  539. $abbrevs[$name] = array($name);
  540. }
  541. return $abbrevs;
  542. }
  543. /**
  544. * Returns a text representation of the Application.
  545. *
  546. * @param string $namespace An optional namespace name
  547. *
  548. * @return string A string representing the Application
  549. */
  550. public function asText($namespace = null)
  551. {
  552. $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
  553. $messages = array($this->getHelp(), '');
  554. if ($namespace) {
  555. $messages[] = sprintf("<comment>Available commands for the \"%s\" namespace:</comment>", $namespace);
  556. } else {
  557. $messages[] = '<comment>Available commands:</comment>';
  558. }
  559. $width = 0;
  560. foreach ($commands as $command) {
  561. $width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
  562. }
  563. $width += 2;
  564. // add commands by namespace
  565. foreach ($this->sortCommands($commands) as $space => $commands) {
  566. if (!$namespace && '_global' !== $space) {
  567. $messages[] = '<comment>'.$space.'</comment>';
  568. }
  569. foreach ($commands as $name => $command) {
  570. $messages[] = sprintf(" <info>%-${width}s</info> %s", $name, $command->getDescription());
  571. }
  572. }
  573. return implode(PHP_EOL, $messages);
  574. }
  575. /**
  576. * Returns an XML representation of the Application.
  577. *
  578. * @param string $namespace An optional namespace name
  579. * @param Boolean $asDom Whether to return a DOM or an XML string
  580. *
  581. * @return string|DOMDocument An XML string representing the Application
  582. */
  583. public function asXml($namespace = null, $asDom = false)
  584. {
  585. $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
  586. $dom = new \DOMDocument('1.0', 'UTF-8');
  587. $dom->formatOutput = true;
  588. $dom->appendChild($xml = $dom->createElement('symfony'));
  589. $xml->appendChild($commandsXML = $dom->createElement('commands'));
  590. if ($namespace) {
  591. $commandsXML->setAttribute('namespace', $namespace);
  592. } else {
  593. $namespacesXML = $dom->createElement('namespaces');
  594. $xml->appendChild($namespacesXML);
  595. }
  596. // add commands by namespace
  597. foreach ($this->sortCommands($commands) as $space => $commands) {
  598. if (!$namespace) {
  599. $namespaceArrayXML = $dom->createElement('namespace');
  600. $namespacesXML->appendChild($namespaceArrayXML);
  601. $namespaceArrayXML->setAttribute('id', $space);
  602. }
  603. foreach ($commands as $name => $command) {
  604. if ($name !== $command->getName()) {
  605. continue;
  606. }
  607. if (!$namespace) {
  608. $commandXML = $dom->createElement('command');
  609. $namespaceArrayXML->appendChild($commandXML);
  610. $commandXML->appendChild($dom->createTextNode($name));
  611. }
  612. $node = $command->asXml(true)->getElementsByTagName('command')->item(0);
  613. $node = $dom->importNode($node, true);
  614. $commandsXML->appendChild($node);
  615. }
  616. }
  617. return $asDom ? $dom : $dom->saveXml();
  618. }
  619. /**
  620. * Renders a catched exception.
  621. *
  622. * @param Exception $e An exception instance
  623. * @param OutputInterface $output An OutputInterface instance
  624. */
  625. public function renderException($e, $output)
  626. {
  627. $strlen = function ($string) {
  628. if (!function_exists('mb_strlen')) {
  629. return strlen($string);
  630. }
  631. if (false === $encoding = mb_detect_encoding($string)) {
  632. return strlen($string);
  633. }
  634. return mb_strlen($string, $encoding);
  635. };
  636. do {
  637. $title = sprintf(' [%s] ', get_class($e));
  638. $len = $strlen($title);
  639. $width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
  640. $lines = array();
  641. foreach (preg_split("{\r?\n}", $e->getMessage()) as $line) {
  642. foreach (str_split($line, $width - 4) as $line) {
  643. $lines[] = sprintf(' %s ', $line);
  644. $len = max($strlen($line) + 4, $len);
  645. }
  646. }
  647. $messages = array(str_repeat(' ', $len), $title.str_repeat(' ', max(0, $len - $strlen($title))));
  648. foreach ($lines as $line) {
  649. $messages[] = $line.str_repeat(' ', $len - $strlen($line));
  650. }
  651. $messages[] = str_repeat(' ', $len);
  652. $output->writeln("\n");
  653. foreach ($messages as $message) {
  654. $output->writeln('<error>'.$message.'</error>');
  655. }
  656. $output->writeln("\n");
  657. if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) {
  658. $output->writeln('<comment>Exception trace:</comment>');
  659. // exception related properties
  660. $trace = $e->getTrace();
  661. array_unshift($trace, array(
  662. 'function' => '',
  663. 'file' => $e->getFile() != null ? $e->getFile() : 'n/a',
  664. 'line' => $e->getLine() != null ? $e->getLine() : 'n/a',
  665. 'args' => array(),
  666. ));
  667. for ($i = 0, $count = count($trace); $i < $count; $i++) {
  668. $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
  669. $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
  670. $function = $trace[$i]['function'];
  671. $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
  672. $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
  673. $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line));
  674. }
  675. $output->writeln("\n");
  676. }
  677. } while ($e = $e->getPrevious());
  678. if (null !== $this->runningCommand) {
  679. $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())));
  680. $output->writeln("");
  681. $output->writeln("");
  682. }
  683. }
  684. /**
  685. * Tries to figure out the terminal width in which this application runs
  686. *
  687. * @return int|null
  688. */
  689. protected function getTerminalWidth()
  690. {
  691. if (defined('PHP_WINDOWS_VERSION_BUILD') && $ansicon = getenv('ANSICON')) {
  692. return preg_replace('{^(\d+)x.*$}', '$1', $ansicon);
  693. }
  694. if (preg_match("{rows.(\d+);.columns.(\d+);}i", exec('stty -a | grep columns'), $match)) {
  695. return $match[1];
  696. }
  697. }
  698. /**
  699. * Tries to figure out the terminal height in which this application runs
  700. *
  701. * @return int|null
  702. */
  703. protected function getTerminalHeight()
  704. {
  705. if (defined('PHP_WINDOWS_VERSION_BUILD') && $ansicon = getenv('ANSICON')) {
  706. return preg_replace('{^\d+x\d+ \(\d+x(\d+)\)$}', '$1', trim($ansicon));
  707. }
  708. if (preg_match("{rows.(\d+);.columns.(\d+);}i", exec('stty -a | grep columns'), $match)) {
  709. return $match[2];
  710. }
  711. }
  712. /**
  713. * Gets the name of the command based on input.
  714. *
  715. * @param InputInterface $input The input interface
  716. *
  717. * @return string The command name
  718. */
  719. protected function getCommandName(InputInterface $input)
  720. {
  721. return $input->getFirstArgument('command');
  722. }
  723. /**
  724. * Sorts commands in alphabetical order.
  725. *
  726. * @param array $commands An associative array of commands to sort
  727. *
  728. * @return array A sorted array of commands
  729. */
  730. private function sortCommands($commands)
  731. {
  732. $namespacedCommands = array();
  733. foreach ($commands as $name => $command) {
  734. $key = $this->extractNamespace($name, 1);
  735. if (!$key) {
  736. $key = '_global';
  737. }
  738. $namespacedCommands[$key][$name] = $command;
  739. }
  740. ksort($namespacedCommands);
  741. foreach ($namespacedCommands as &$commands) {
  742. ksort($commands);
  743. }
  744. return $namespacedCommands;
  745. }
  746. /**
  747. * Returns abbreviated suggestions in string format.
  748. *
  749. * @param array $abbrevs Abbreviated suggestions to convert
  750. *
  751. * @return string A formatted string of abbreviated suggestions
  752. */
  753. private function getAbbreviationSuggestions($abbrevs)
  754. {
  755. return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
  756. }
  757. /**
  758. * Returns the namespace part of the command name.
  759. *
  760. * @param string $name The full name of the command
  761. * @param string $limit The maximum number of parts of the namespace
  762. *
  763. * @return string The namespace of the command
  764. */
  765. private function extractNamespace($name, $limit = null)
  766. {
  767. $parts = explode(':', $name);
  768. array_pop($parts);
  769. return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
  770. }
  771. }