Application.php 38 KB

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