Application.php 38 KB

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