Application.php 38 KB

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