No Description

Application.php 37KB

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