Drupal investigation

Application.php 38KB

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