Application.php 38 KB

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