Application.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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. /**
  28. * An Application is the container for a collection of commands.
  29. *
  30. * It is the main entry point of a Console application.
  31. *
  32. * This class is optimized for a standard CLI environment.
  33. *
  34. * Usage:
  35. *
  36. * $app = new Application('myapp', '1.0 (stable)');
  37. * $app->add(new SimpleCommand());
  38. * $app->run();
  39. *
  40. * @author Fabien Potencier <fabien@symfony.com>
  41. *
  42. * @api
  43. */
  44. class Application
  45. {
  46. private $commands;
  47. private $wantHelps = false;
  48. private $runningCommand;
  49. private $name;
  50. private $version;
  51. private $catchExceptions;
  52. private $autoExit;
  53. private $definition;
  54. private $helperSet;
  55. /**
  56. * Constructor.
  57. *
  58. * @param string $name The name of the application
  59. * @param string $version The version of the application
  60. *
  61. * @api
  62. */
  63. public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
  64. {
  65. $this->name = $name;
  66. $this->version = $version;
  67. $this->catchExceptions = true;
  68. $this->autoExit = true;
  69. $this->commands = array();
  70. $this->helperSet = $this->getDefaultHelperSet();
  71. $this->definition = $this->getDefaultInputDefinition();
  72. foreach ($this->getDefaultCommands() as $command) {
  73. $this->add($command);
  74. }
  75. }
  76. /**
  77. * Runs the current application.
  78. *
  79. * @param InputInterface $input An Input instance
  80. * @param OutputInterface $output An Output instance
  81. *
  82. * @return integer 0 if everything went fine, or an error code
  83. *
  84. * @throws \Exception When doRun returns Exception
  85. *
  86. * @api
  87. */
  88. public function run(InputInterface $input = null, OutputInterface $output = null)
  89. {
  90. if (null === $input) {
  91. $input = new ArgvInput();
  92. }
  93. if (null === $output) {
  94. $output = new ConsoleOutput();
  95. }
  96. try {
  97. $statusCode = $this->doRun($input, $output);
  98. } catch (\Exception $e) {
  99. if (!$this->catchExceptions) {
  100. throw $e;
  101. }
  102. if ($output instanceof ConsoleOutputInterface) {
  103. $this->renderException($e, $output->getErrorOutput());
  104. } else {
  105. $this->renderException($e, $output);
  106. }
  107. $statusCode = $e->getCode();
  108. $statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1;
  109. }
  110. if ($this->autoExit) {
  111. if ($statusCode > 255) {
  112. $statusCode = 255;
  113. }
  114. // @codeCoverageIgnoreStart
  115. exit($statusCode);
  116. // @codeCoverageIgnoreEnd
  117. }
  118. return $statusCode;
  119. }
  120. /**
  121. * Runs the current application.
  122. *
  123. * @param InputInterface $input An Input instance
  124. * @param OutputInterface $output An Output instance
  125. *
  126. * @return integer 0 if everything went fine, or an error code
  127. */
  128. public function doRun(InputInterface $input, OutputInterface $output)
  129. {
  130. $name = $this->getCommandName($input);
  131. if (true === $input->hasParameterOption(array('--ansi'))) {
  132. $output->setDecorated(true);
  133. } elseif (true === $input->hasParameterOption(array('--no-ansi'))) {
  134. $output->setDecorated(false);
  135. }
  136. if (true === $input->hasParameterOption(array('--help', '-h'))) {
  137. if (!$name) {
  138. $name = 'help';
  139. $input = new ArrayInput(array('command' => 'help'));
  140. } else {
  141. $this->wantHelps = true;
  142. }
  143. }
  144. if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
  145. $input->setInteractive(false);
  146. }
  147. if (function_exists('posix_isatty') && $this->getHelperSet()->has('dialog')) {
  148. $inputStream = $this->getHelperSet()->get('dialog')->getInputStream();
  149. if (!posix_isatty($inputStream)) {
  150. $input->setInteractive(false);
  151. }
  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(PHP_EOL, $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. if (!$command->isEnabled()) {
  348. $command->setApplication(null);
  349. return;
  350. }
  351. $this->commands[$command->getName()] = $command;
  352. foreach ($command->getAliases() as $alias) {
  353. $this->commands[$alias] = $command;
  354. }
  355. return $command;
  356. }
  357. /**
  358. * Returns a registered command by name or alias.
  359. *
  360. * @param string $name The command name or alias
  361. *
  362. * @return Command A Command object
  363. *
  364. * @throws \InvalidArgumentException When command name given does not exist
  365. *
  366. * @api
  367. */
  368. public function get($name)
  369. {
  370. if (!isset($this->commands[$name])) {
  371. throw new \InvalidArgumentException(sprintf('The command "%s" does not exist.', $name));
  372. }
  373. $command = $this->commands[$name];
  374. if ($this->wantHelps) {
  375. $this->wantHelps = false;
  376. $helpCommand = $this->get('help');
  377. $helpCommand->setCommand($command);
  378. return $helpCommand;
  379. }
  380. return $command;
  381. }
  382. /**
  383. * Returns true if the command exists, false otherwise.
  384. *
  385. * @param string $name The command name or alias
  386. *
  387. * @return Boolean true if the command exists, false otherwise
  388. *
  389. * @api
  390. */
  391. public function has($name)
  392. {
  393. return isset($this->commands[$name]);
  394. }
  395. /**
  396. * Returns an array of all unique namespaces used by currently registered commands.
  397. *
  398. * It does not returns the global namespace which always exists.
  399. *
  400. * @return array An array of namespaces
  401. */
  402. public function getNamespaces()
  403. {
  404. $namespaces = array();
  405. foreach ($this->commands as $command) {
  406. $namespaces[] = $this->extractNamespace($command->getName());
  407. foreach ($command->getAliases() as $alias) {
  408. $namespaces[] = $this->extractNamespace($alias);
  409. }
  410. }
  411. return array_values(array_unique(array_filter($namespaces)));
  412. }
  413. /**
  414. * Finds a registered namespace by a name or an abbreviation.
  415. *
  416. * @param string $namespace A namespace or abbreviation to search for
  417. *
  418. * @return string A registered namespace
  419. *
  420. * @throws \InvalidArgumentException When namespace is incorrect or ambiguous
  421. */
  422. public function findNamespace($namespace)
  423. {
  424. $allNamespaces = array();
  425. foreach ($this->getNamespaces() as $n) {
  426. $allNamespaces[$n] = explode(':', $n);
  427. }
  428. $found = array();
  429. foreach (explode(':', $namespace) as $i => $part) {
  430. $abbrevs = static::getAbbreviations(array_unique(array_values(array_filter(array_map(function ($p) use ($i) { return isset($p[$i]) ? $p[$i] : ''; }, $allNamespaces)))));
  431. if (!isset($abbrevs[$part])) {
  432. $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
  433. if (1 <= $i) {
  434. $part = implode(':', $found).':'.$part;
  435. }
  436. if ($alternatives = $this->findAlternativeNamespace($part, $abbrevs)) {
  437. $message .= "\n\nDid you mean one of these?\n ";
  438. $message .= implode("\n ", $alternatives);
  439. }
  440. throw new \InvalidArgumentException($message);
  441. }
  442. if (count($abbrevs[$part]) > 1) {
  443. throw new \InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions($abbrevs[$part])));
  444. }
  445. $found[] = $abbrevs[$part][0];
  446. }
  447. return implode(':', $found);
  448. }
  449. /**
  450. * Finds a command by name or alias.
  451. *
  452. * Contrary to get, this command tries to find the best
  453. * match if you give it an abbreviation of a name or alias.
  454. *
  455. * @param string $name A command name or a command alias
  456. *
  457. * @return Command A Command instance
  458. *
  459. * @throws \InvalidArgumentException When command name is incorrect or ambiguous
  460. *
  461. * @api
  462. */
  463. public function find($name)
  464. {
  465. // namespace
  466. $namespace = '';
  467. $searchName = $name;
  468. if (false !== $pos = strrpos($name, ':')) {
  469. $namespace = $this->findNamespace(substr($name, 0, $pos));
  470. $searchName = $namespace.substr($name, $pos);
  471. }
  472. // name
  473. $commands = array();
  474. foreach ($this->commands as $command) {
  475. if ($this->extractNamespace($command->getName()) == $namespace) {
  476. $commands[] = $command->getName();
  477. }
  478. }
  479. $abbrevs = static::getAbbreviations(array_unique($commands));
  480. if (isset($abbrevs[$searchName]) && 1 == count($abbrevs[$searchName])) {
  481. return $this->get($abbrevs[$searchName][0]);
  482. }
  483. if (isset($abbrevs[$searchName]) && count($abbrevs[$searchName]) > 1) {
  484. $suggestions = $this->getAbbreviationSuggestions($abbrevs[$searchName]);
  485. throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions));
  486. }
  487. // aliases
  488. $aliases = array();
  489. foreach ($this->commands as $command) {
  490. foreach ($command->getAliases() as $alias) {
  491. if ($this->extractNamespace($alias) == $namespace) {
  492. $aliases[] = $alias;
  493. }
  494. }
  495. }
  496. $aliases = static::getAbbreviations(array_unique($aliases));
  497. if (!isset($aliases[$searchName])) {
  498. $message = sprintf('Command "%s" is not defined.', $name);
  499. if ($alternatives = $this->findAlternativeCommands($searchName, $abbrevs)) {
  500. $message .= "\n\nDid you mean one of these?\n ";
  501. $message .= implode("\n ", $alternatives);
  502. }
  503. throw new \InvalidArgumentException($message);
  504. }
  505. if (count($aliases[$searchName]) > 1) {
  506. throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $this->getAbbreviationSuggestions($aliases[$searchName])));
  507. }
  508. return $this->get($aliases[$searchName][0]);
  509. }
  510. /**
  511. * Gets the commands (registered in the given namespace if provided).
  512. *
  513. * The array keys are the full names and the values the command instances.
  514. *
  515. * @param string $namespace A namespace name
  516. *
  517. * @return array An array of Command instances
  518. *
  519. * @api
  520. */
  521. public function all($namespace = null)
  522. {
  523. if (null === $namespace) {
  524. return $this->commands;
  525. }
  526. $commands = array();
  527. foreach ($this->commands as $name => $command) {
  528. if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
  529. $commands[$name] = $command;
  530. }
  531. }
  532. return $commands;
  533. }
  534. /**
  535. * Returns an array of possible abbreviations given a set of names.
  536. *
  537. * @param array $names An array of names
  538. *
  539. * @return array An array of abbreviations
  540. */
  541. static public function getAbbreviations($names)
  542. {
  543. $abbrevs = array();
  544. foreach ($names as $name) {
  545. for ($len = strlen($name) - 1; $len > 0; --$len) {
  546. $abbrev = substr($name, 0, $len);
  547. if (!isset($abbrevs[$abbrev])) {
  548. $abbrevs[$abbrev] = array($name);
  549. } else {
  550. $abbrevs[$abbrev][] = $name;
  551. }
  552. }
  553. }
  554. // Non-abbreviations always get entered, even if they aren't unique
  555. foreach ($names as $name) {
  556. $abbrevs[$name] = array($name);
  557. }
  558. return $abbrevs;
  559. }
  560. /**
  561. * Returns a text representation of the Application.
  562. *
  563. * @param string $namespace An optional namespace name
  564. * @param boolean $raw Whether to return raw command list
  565. *
  566. * @return string A string representing the Application
  567. */
  568. public function asText($namespace = null, $raw = false)
  569. {
  570. $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
  571. $width = 0;
  572. foreach ($commands as $command) {
  573. $width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
  574. }
  575. $width += 2;
  576. if ($raw) {
  577. $messages = array();
  578. foreach ($this->sortCommands($commands) as $space => $commands) {
  579. foreach ($commands as $name => $command) {
  580. $messages[] = sprintf("%-${width}s %s", $name, $command->getDescription());
  581. }
  582. }
  583. return implode(PHP_EOL, $messages);
  584. }
  585. $messages = array($this->getHelp(), '');
  586. if ($namespace) {
  587. $messages[] = sprintf("<comment>Available commands for the \"%s\" namespace:</comment>", $namespace);
  588. } else {
  589. $messages[] = '<comment>Available commands:</comment>';
  590. }
  591. // add commands by namespace
  592. foreach ($this->sortCommands($commands) as $space => $commands) {
  593. if (!$namespace && '_global' !== $space) {
  594. $messages[] = '<comment>'.$space.'</comment>';
  595. }
  596. foreach ($commands as $name => $command) {
  597. $messages[] = sprintf(" <info>%-${width}s</info> %s", $name, $command->getDescription());
  598. }
  599. }
  600. return implode(PHP_EOL, $messages);
  601. }
  602. /**
  603. * Returns an XML representation of the Application.
  604. *
  605. * @param string $namespace An optional namespace name
  606. * @param Boolean $asDom Whether to return a DOM or an XML string
  607. *
  608. * @return string|DOMDocument An XML string representing the Application
  609. */
  610. public function asXml($namespace = null, $asDom = false)
  611. {
  612. $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
  613. $dom = new \DOMDocument('1.0', 'UTF-8');
  614. $dom->formatOutput = true;
  615. $dom->appendChild($xml = $dom->createElement('symfony'));
  616. $xml->appendChild($commandsXML = $dom->createElement('commands'));
  617. if ($namespace) {
  618. $commandsXML->setAttribute('namespace', $namespace);
  619. } else {
  620. $namespacesXML = $dom->createElement('namespaces');
  621. $xml->appendChild($namespacesXML);
  622. }
  623. // add commands by namespace
  624. foreach ($this->sortCommands($commands) as $space => $commands) {
  625. if (!$namespace) {
  626. $namespaceArrayXML = $dom->createElement('namespace');
  627. $namespacesXML->appendChild($namespaceArrayXML);
  628. $namespaceArrayXML->setAttribute('id', $space);
  629. }
  630. foreach ($commands as $name => $command) {
  631. if ($name !== $command->getName()) {
  632. continue;
  633. }
  634. if (!$namespace) {
  635. $commandXML = $dom->createElement('command');
  636. $namespaceArrayXML->appendChild($commandXML);
  637. $commandXML->appendChild($dom->createTextNode($name));
  638. }
  639. $node = $command->asXml(true)->getElementsByTagName('command')->item(0);
  640. $node = $dom->importNode($node, true);
  641. $commandsXML->appendChild($node);
  642. }
  643. }
  644. return $asDom ? $dom : $dom->saveXml();
  645. }
  646. /**
  647. * Renders a catched exception.
  648. *
  649. * @param Exception $e An exception instance
  650. * @param OutputInterface $output An OutputInterface instance
  651. */
  652. public function renderException($e, $output)
  653. {
  654. $strlen = function ($string) {
  655. if (!function_exists('mb_strlen')) {
  656. return strlen($string);
  657. }
  658. if (false === $encoding = mb_detect_encoding($string)) {
  659. return strlen($string);
  660. }
  661. return mb_strlen($string, $encoding);
  662. };
  663. do {
  664. $title = sprintf(' [%s] ', get_class($e));
  665. $len = $strlen($title);
  666. $lines = array();
  667. foreach (explode("\n", $e->getMessage()) as $line) {
  668. $lines[] = sprintf(' %s ', $line);
  669. $len = max($strlen($line) + 4, $len);
  670. }
  671. $messages = array(str_repeat(' ', $len), $title.str_repeat(' ', $len - $strlen($title)));
  672. foreach ($lines as $line) {
  673. $messages[] = $line.str_repeat(' ', $len - $strlen($line));
  674. }
  675. $messages[] = str_repeat(' ', $len);
  676. $output->writeln("");
  677. $output->writeln("");
  678. foreach ($messages as $message) {
  679. $output->writeln('<error>'.$message.'</error>');
  680. }
  681. $output->writeln("");
  682. $output->writeln("");
  683. if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) {
  684. $output->writeln('<comment>Exception trace:</comment>');
  685. // exception related properties
  686. $trace = $e->getTrace();
  687. array_unshift($trace, array(
  688. 'function' => '',
  689. 'file' => $e->getFile() != null ? $e->getFile() : 'n/a',
  690. 'line' => $e->getLine() != null ? $e->getLine() : 'n/a',
  691. 'args' => array(),
  692. ));
  693. for ($i = 0, $count = count($trace); $i < $count; $i++) {
  694. $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
  695. $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
  696. $function = $trace[$i]['function'];
  697. $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
  698. $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
  699. $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line));
  700. }
  701. $output->writeln("");
  702. $output->writeln("");
  703. }
  704. } while ($e = $e->getPrevious());
  705. if (null !== $this->runningCommand) {
  706. $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())));
  707. $output->writeln("");
  708. $output->writeln("");
  709. }
  710. }
  711. /**
  712. * Gets the name of the command based on input.
  713. *
  714. * @param InputInterface $input The input interface
  715. *
  716. * @return string The command name
  717. */
  718. protected function getCommandName(InputInterface $input)
  719. {
  720. return $input->getFirstArgument('command');
  721. }
  722. /**
  723. * Gets the default input definition.
  724. *
  725. * @return InputDefinition An InputDefinition instance
  726. */
  727. protected function getDefaultInputDefinition()
  728. {
  729. return new InputDefinition(array(
  730. new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
  731. new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
  732. new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message.'),
  733. new InputOption('--verbose', '-v', InputOption::VALUE_NONE, 'Increase verbosity of messages.'),
  734. new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version.'),
  735. new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output.'),
  736. new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output.'),
  737. new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question.'),
  738. ));
  739. }
  740. /**
  741. * Gets the default commands that should always be available.
  742. *
  743. * @return array An array of default Command instances
  744. */
  745. protected function getDefaultCommands()
  746. {
  747. return array(new HelpCommand(), new ListCommand());
  748. }
  749. /**
  750. * Gets the default helper set with the helpers that should always be available.
  751. *
  752. * @return HelperSet A HelperSet instance
  753. */
  754. protected function getDefaultHelperSet()
  755. {
  756. return new HelperSet(array(
  757. new FormatterHelper(),
  758. new DialogHelper(),
  759. ));
  760. }
  761. /**
  762. * Sorts commands in alphabetical order.
  763. *
  764. * @param array $commands An associative array of commands to sort
  765. *
  766. * @return array A sorted array of commands
  767. */
  768. private function sortCommands($commands)
  769. {
  770. $namespacedCommands = array();
  771. foreach ($commands as $name => $command) {
  772. $key = $this->extractNamespace($name, 1);
  773. if (!$key) {
  774. $key = '_global';
  775. }
  776. $namespacedCommands[$key][$name] = $command;
  777. }
  778. ksort($namespacedCommands);
  779. foreach ($namespacedCommands as &$commands) {
  780. ksort($commands);
  781. }
  782. return $namespacedCommands;
  783. }
  784. /**
  785. * Returns abbreviated suggestions in string format.
  786. *
  787. * @param array $abbrevs Abbreviated suggestions to convert
  788. *
  789. * @return string A formatted string of abbreviated suggestions
  790. */
  791. private function getAbbreviationSuggestions($abbrevs)
  792. {
  793. return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
  794. }
  795. /**
  796. * Returns the namespace part of the command name.
  797. *
  798. * @param string $name The full name of the command
  799. * @param string $limit The maximum number of parts of the namespace
  800. *
  801. * @return string The namespace of the command
  802. */
  803. private function extractNamespace($name, $limit = null)
  804. {
  805. $parts = explode(':', $name);
  806. array_pop($parts);
  807. return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
  808. }
  809. /**
  810. * Finds alternative commands of $name
  811. *
  812. * @param string $name The full name of the command
  813. * @param array $abbrevs The abbreviations
  814. *
  815. * @return array A sorted array of similar commands
  816. */
  817. private function findAlternativeCommands($name, $abbrevs)
  818. {
  819. $callback = function($item) {
  820. return $item->getName();
  821. };
  822. return $this->findAlternatives($name, $this->commands, $abbrevs, $callback);
  823. }
  824. /**
  825. * Finds alternative namespace of $name
  826. *
  827. * @param string $name The full name of the namespace
  828. * @param array $abbrevs The abbreviations
  829. *
  830. * @return array A sorted array of similar namespace
  831. */
  832. private function findAlternativeNamespace($name, $abbrevs)
  833. {
  834. return $this->findAlternatives($name, $this->getNamespaces(), $abbrevs);
  835. }
  836. /**
  837. * Finds alternative of $name among $collection,
  838. * if nothing is found in $collection, try in $abbrevs
  839. *
  840. * @param string $name The string
  841. * @param array|Traversable $collection The collecion
  842. * @param array $abbrevs The abbreviations
  843. * @param Closure|string|array $callback The callable to transform collection item before comparison
  844. *
  845. * @return array A sorted array of similar string
  846. */
  847. private function findAlternatives($name, $collection, $abbrevs, $callback = null) {
  848. $alternatives = array();
  849. foreach ($collection as $item) {
  850. if (null !== $callback) {
  851. $item = call_user_func($callback, $item);
  852. }
  853. $lev = levenshtein($name, $item);
  854. if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
  855. $alternatives[$item] = $lev;
  856. }
  857. }
  858. if (!$alternatives) {
  859. foreach ($abbrevs as $key => $values) {
  860. $lev = levenshtein($name, $key);
  861. if ($lev <= strlen($name) / 3 || false !== strpos($key, $name)) {
  862. foreach ($values as $value) {
  863. $alternatives[$value] = $lev;
  864. }
  865. }
  866. }
  867. }
  868. asort($alternatives);
  869. return array_keys($alternatives);
  870. }
  871. }