菜谱项目

Application.php 37KB

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