Application.php 37 KB

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