Application.php 37 KB

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