Application.php 38 KB

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