SymfonyStyle.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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\Style;
  11. use Symfony\Component\Console\Exception\InvalidArgumentException;
  12. use Symfony\Component\Console\Exception\RuntimeException;
  13. use Symfony\Component\Console\Formatter\OutputFormatter;
  14. use Symfony\Component\Console\Helper\Helper;
  15. use Symfony\Component\Console\Helper\OutputWrapper;
  16. use Symfony\Component\Console\Helper\ProgressBar;
  17. use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
  18. use Symfony\Component\Console\Helper\Table;
  19. use Symfony\Component\Console\Helper\TableCell;
  20. use Symfony\Component\Console\Helper\TableSeparator;
  21. use Symfony\Component\Console\Input\InputInterface;
  22. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  23. use Symfony\Component\Console\Output\ConsoleSectionOutput;
  24. use Symfony\Component\Console\Output\OutputInterface;
  25. use Symfony\Component\Console\Output\TrimmedBufferOutput;
  26. use Symfony\Component\Console\Question\ChoiceQuestion;
  27. use Symfony\Component\Console\Question\ConfirmationQuestion;
  28. use Symfony\Component\Console\Question\Question;
  29. use Symfony\Component\Console\Terminal;
  30. /**
  31. * Output decorator helpers for the Symfony Style Guide.
  32. *
  33. * @author Kevin Bond <kevinbond@gmail.com>
  34. */
  35. class SymfonyStyle extends OutputStyle
  36. {
  37. public const MAX_LINE_LENGTH = 120;
  38. /**
  39. * @var \Symfony\Component\Console\Input\InputInterface
  40. */
  41. private $input;
  42. /**
  43. * @var \Symfony\Component\Console\Output\OutputInterface
  44. */
  45. private $output;
  46. /**
  47. * @var \Symfony\Component\Console\Helper\SymfonyQuestionHelper
  48. */
  49. private $questionHelper;
  50. /**
  51. * @var \Symfony\Component\Console\Helper\ProgressBar
  52. */
  53. private $progressBar;
  54. /**
  55. * @var int
  56. */
  57. private $lineLength;
  58. /**
  59. * @var \Symfony\Component\Console\Output\TrimmedBufferOutput
  60. */
  61. private $bufferedOutput;
  62. /**
  63. * @param \Symfony\Component\Console\Input\InputInterface $input
  64. * @param \Symfony\Component\Console\Output\OutputInterface $output
  65. */
  66. public function __construct($input, $output)
  67. {
  68. $this->input = $input;
  69. $this->bufferedOutput = new TrimmedBufferOutput(\DIRECTORY_SEPARATOR === '\\' ? 4 : 2, $output->getVerbosity(), false, clone $output->getFormatter());
  70. // Windows cmd wraps lines as soon as the terminal width is reached, whether there are following chars or not.
  71. $width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH;
  72. $this->lineLength = min($width - (int) (\DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
  73. parent::__construct($this->output = $output);
  74. }
  75. /**
  76. * Formats a message as a block of text.
  77. *
  78. * @return void
  79. * @param string|mixed[] $messages
  80. * @param string|null $type
  81. * @param string|null $style
  82. * @param string $prefix
  83. * @param bool $padding
  84. * @param bool $escape
  85. */
  86. public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = true)
  87. {
  88. $messages = \is_array($messages) ? array_values($messages) : [$messages];
  89. $this->autoPrependBlock();
  90. $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, $escape));
  91. $this->newLine();
  92. }
  93. /**
  94. * @return void
  95. * @param string $message
  96. */
  97. public function title($message)
  98. {
  99. $this->autoPrependBlock();
  100. $this->writeln([
  101. sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
  102. sprintf('<comment>%s</>', str_repeat('=', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))),
  103. ]);
  104. $this->newLine();
  105. }
  106. /**
  107. * @return void
  108. * @param string $message
  109. */
  110. public function section($message)
  111. {
  112. $this->autoPrependBlock();
  113. $this->writeln([
  114. sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
  115. sprintf('<comment>%s</>', str_repeat('-', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))),
  116. ]);
  117. $this->newLine();
  118. }
  119. /**
  120. * @return void
  121. * @param mixed[] $elements
  122. */
  123. public function listing($elements)
  124. {
  125. $this->autoPrependText();
  126. $elements = array_map(function ($element) {
  127. return sprintf(' * %s', $element);
  128. }, $elements);
  129. $this->writeln($elements);
  130. $this->newLine();
  131. }
  132. /**
  133. * @return void
  134. * @param string|mixed[] $message
  135. */
  136. public function text($message)
  137. {
  138. $this->autoPrependText();
  139. $messages = \is_array($message) ? array_values($message) : [$message];
  140. foreach ($messages as $message) {
  141. $this->writeln(sprintf(' %s', $message));
  142. }
  143. }
  144. /**
  145. * Formats a command comment.
  146. *
  147. * @return void
  148. * @param string|mixed[] $message
  149. */
  150. public function comment($message)
  151. {
  152. $this->block($message, null, null, '<fg=default;bg=default> // </>', false, false);
  153. }
  154. /**
  155. * @return void
  156. * @param string|mixed[] $message
  157. */
  158. public function success($message)
  159. {
  160. $this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
  161. }
  162. /**
  163. * @return void
  164. * @param string|mixed[] $message
  165. */
  166. public function error($message)
  167. {
  168. $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
  169. }
  170. /**
  171. * @return void
  172. * @param string|mixed[] $message
  173. */
  174. public function warning($message)
  175. {
  176. $this->block($message, 'WARNING', 'fg=black;bg=yellow', ' ', true);
  177. }
  178. /**
  179. * @return void
  180. * @param string|mixed[] $message
  181. */
  182. public function note($message)
  183. {
  184. $this->block($message, 'NOTE', 'fg=yellow', ' ! ');
  185. }
  186. /**
  187. * Formats an info message.
  188. *
  189. * @return void
  190. * @param string|mixed[] $message
  191. */
  192. public function info($message)
  193. {
  194. $this->block($message, 'INFO', 'fg=green', ' ', true);
  195. }
  196. /**
  197. * @return void
  198. * @param string|mixed[] $message
  199. */
  200. public function caution($message)
  201. {
  202. $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
  203. }
  204. /**
  205. * @return void
  206. * @param mixed[] $headers
  207. * @param mixed[] $rows
  208. */
  209. public function table($headers, $rows)
  210. {
  211. $this->createTable()
  212. ->setHeaders($headers)
  213. ->setRows($rows)
  214. ->render()
  215. ;
  216. $this->newLine();
  217. }
  218. /**
  219. * Formats a horizontal table.
  220. *
  221. * @return void
  222. * @param mixed[] $headers
  223. * @param mixed[] $rows
  224. */
  225. public function horizontalTable($headers, $rows)
  226. {
  227. $this->createTable()
  228. ->setHorizontal(true)
  229. ->setHeaders($headers)
  230. ->setRows($rows)
  231. ->render()
  232. ;
  233. $this->newLine();
  234. }
  235. /**
  236. * Formats a list of key/value horizontally.
  237. *
  238. * Each row can be one of:
  239. * * 'A title'
  240. * * ['key' => 'value']
  241. * * new TableSeparator()
  242. *
  243. * @return void
  244. * @param string|mixed[]|\Symfony\Component\Console\Helper\TableSeparator ...$list
  245. */
  246. public function definitionList(...$list)
  247. {
  248. $headers = [];
  249. $row = [];
  250. foreach ($list as $value) {
  251. if ($value instanceof TableSeparator) {
  252. $headers[] = $value;
  253. $row[] = $value;
  254. continue;
  255. }
  256. if (\is_string($value)) {
  257. $headers[] = new TableCell($value, ['colspan' => 2]);
  258. $row[] = null;
  259. continue;
  260. }
  261. if (!\is_array($value)) {
  262. throw new InvalidArgumentException('Value should be an array, string, or an instance of TableSeparator.');
  263. }
  264. $headers[] = key($value);
  265. $row[] = current($value);
  266. }
  267. $this->horizontalTable($headers, [$row]);
  268. }
  269. /**
  270. * @return mixed
  271. * @param string $question
  272. * @param string|null $default
  273. * @param callable|null $validator
  274. */
  275. public function ask($question, $default = null, $validator = null)
  276. {
  277. $question = new Question($question, $default);
  278. $question->setValidator($validator);
  279. return $this->askQuestion($question);
  280. }
  281. /**
  282. * @return mixed
  283. * @param string $question
  284. * @param callable|null $validator
  285. */
  286. public function askHidden($question, $validator = null)
  287. {
  288. $question = new Question($question);
  289. $question->setHidden(true);
  290. $question->setValidator($validator);
  291. return $this->askQuestion($question);
  292. }
  293. /**
  294. * @param string $question
  295. * @param bool $default
  296. */
  297. public function confirm($question, $default = true)
  298. {
  299. return $this->askQuestion(new ConfirmationQuestion($question, $default));
  300. }
  301. /**
  302. * @param mixed $default
  303. * @return mixed
  304. * @param string $question
  305. * @param mixed[] $choices
  306. * @param bool $multiSelect
  307. */
  308. public function choice($question, $choices, $default = null, $multiSelect = false)
  309. {
  310. if (null !== $default) {
  311. $values = array_flip($choices);
  312. $default = $values[$default] ?? $default;
  313. }
  314. $questionChoice = new ChoiceQuestion($question, $choices, $default);
  315. $questionChoice->setMultiselect($multiSelect);
  316. return $this->askQuestion($questionChoice);
  317. }
  318. /**
  319. * @return void
  320. * @param int $max
  321. */
  322. public function progressStart($max = 0)
  323. {
  324. $this->progressBar = $this->createProgressBar($max);
  325. $this->progressBar->start();
  326. }
  327. /**
  328. * @return void
  329. * @param int $step
  330. */
  331. public function progressAdvance($step = 1)
  332. {
  333. $this->getProgressBar()->advance($step);
  334. }
  335. /**
  336. * @return void
  337. */
  338. public function progressFinish()
  339. {
  340. $this->getProgressBar()->finish();
  341. $this->newLine(2);
  342. unset($this->progressBar);
  343. }
  344. /**
  345. * @param int $max
  346. */
  347. public function createProgressBar($max = 0)
  348. {
  349. $progressBar = parent::createProgressBar($max);
  350. if ('\\' !== \DIRECTORY_SEPARATOR || 'Hyper' === getenv('TERM_PROGRAM')) {
  351. $progressBar->setEmptyBarCharacter('░'); // light shade character \u2591
  352. $progressBar->setProgressCharacter('');
  353. $progressBar->setBarCharacter('▓'); // dark shade character \u2593
  354. }
  355. return $progressBar;
  356. }
  357. /**
  358. * @see ProgressBar::iterate()
  359. * @param mixed[] $iterable
  360. * @param int|null $max
  361. */
  362. public function progressIterate($iterable, $max = null)
  363. {
  364. yield from $this->createProgressBar()->iterate($iterable, $max);
  365. $this->newLine(2);
  366. }
  367. /**
  368. * @return mixed
  369. * @param \Symfony\Component\Console\Question\Question $question
  370. */
  371. public function askQuestion($question)
  372. {
  373. if ($this->input->isInteractive()) {
  374. $this->autoPrependBlock();
  375. }
  376. $this->questionHelper = $this->questionHelper ?? new SymfonyQuestionHelper();
  377. $answer = $this->questionHelper->ask($this->input, $this, $question);
  378. if ($this->input->isInteractive()) {
  379. if ($this->output instanceof ConsoleSectionOutput) {
  380. // add the new line of the `return` to submit the input to ConsoleSectionOutput, because ConsoleSectionOutput is holding all it's lines.
  381. // this is relevant when a `ConsoleSectionOutput::clear` is called.
  382. $this->output->addNewLineOfInputSubmit();
  383. }
  384. $this->newLine();
  385. $this->bufferedOutput->write("\n");
  386. }
  387. return $answer;
  388. }
  389. /**
  390. * @return void
  391. * @param string|mixed[] $messages
  392. * @param int $type
  393. */
  394. public function writeln($messages, $type = self::OUTPUT_NORMAL)
  395. {
  396. if (!is_iterable($messages)) {
  397. $messages = [$messages];
  398. }
  399. foreach ($messages as $message) {
  400. parent::writeln($message, $type);
  401. $this->writeBuffer($message, true, $type);
  402. }
  403. }
  404. /**
  405. * @return void
  406. * @param string|mixed[] $messages
  407. * @param bool $newline
  408. * @param int $type
  409. */
  410. public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
  411. {
  412. if (!is_iterable($messages)) {
  413. $messages = [$messages];
  414. }
  415. foreach ($messages as $message) {
  416. parent::write($message, $newline, $type);
  417. $this->writeBuffer($message, $newline, $type);
  418. }
  419. }
  420. /**
  421. * @return void
  422. * @param int $count
  423. */
  424. public function newLine($count = 1)
  425. {
  426. parent::newLine($count);
  427. $this->bufferedOutput->write(str_repeat("\n", $count));
  428. }
  429. /**
  430. * Returns a new instance which makes use of stderr if available.
  431. */
  432. public function getErrorStyle()
  433. {
  434. return new self($this->input, $this->getErrorOutput());
  435. }
  436. public function createTable()
  437. {
  438. $output = $this->output instanceof ConsoleOutputInterface ? $this->output->section() : $this->output;
  439. $style = clone Table::getStyleDefinition('symfony-style-guide');
  440. $style->setCellHeaderFormat('<info>%s</info>');
  441. return (new Table($output))->setStyle($style);
  442. }
  443. private function getProgressBar()
  444. {
  445. if (!isset($this->progressBar)) {
  446. throw new RuntimeException('The ProgressBar is not started.');
  447. }
  448. return $this->progressBar;
  449. }
  450. private function autoPrependBlock()
  451. {
  452. $chars = substr(str_replace(\PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
  453. if (!isset($chars[0])) {
  454. $this->newLine(); // empty history, so we should start with a new line.
  455. return;
  456. }
  457. // Prepend new line for each non LF chars (This means no blank line was output before)
  458. $this->newLine(2 - substr_count($chars, "\n"));
  459. }
  460. private function autoPrependText()
  461. {
  462. $fetched = $this->bufferedOutput->fetch();
  463. // Prepend new line if last char isn't EOL:
  464. if ($fetched && substr_compare($fetched, "\n", -strlen("\n")) !== 0) {
  465. $this->newLine();
  466. }
  467. }
  468. /**
  469. * @param string $message
  470. * @param bool $newLine
  471. * @param int $type
  472. */
  473. private function writeBuffer($message, $newLine, $type)
  474. {
  475. // We need to know if the last chars are PHP_EOL
  476. $this->bufferedOutput->write($message, $newLine, $type);
  477. }
  478. /**
  479. * @param mixed[] $messages
  480. * @param string|null $type
  481. * @param string|null $style
  482. * @param string $prefix
  483. * @param bool $padding
  484. * @param bool $escape
  485. */
  486. private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false)
  487. {
  488. $indentLength = 0;
  489. $prefixLength = Helper::width(Helper::removeDecoration($this->getFormatter(), $prefix));
  490. $lines = [];
  491. if (null !== $type) {
  492. $type = sprintf('[%s] ', $type);
  493. $indentLength = Helper::width($type);
  494. $lineIndentation = str_repeat(' ', $indentLength);
  495. }
  496. // wrap and add newlines for each element
  497. $outputWrapper = new OutputWrapper();
  498. foreach ($messages as $key => $message) {
  499. if ($escape) {
  500. $message = OutputFormatter::escape($message);
  501. }
  502. $lines = array_merge(
  503. $lines,
  504. explode(\PHP_EOL, $outputWrapper->wrap(
  505. $message,
  506. $this->lineLength - $prefixLength - $indentLength,
  507. \PHP_EOL
  508. ))
  509. );
  510. if (\count($messages) > 1 && $key < \count($messages) - 1) {
  511. $lines[] = '';
  512. }
  513. }
  514. $firstLineIndex = 0;
  515. if ($padding && $this->isDecorated()) {
  516. $firstLineIndex = 1;
  517. array_unshift($lines, '');
  518. $lines[] = '';
  519. }
  520. foreach ($lines as $i => &$line) {
  521. if (null !== $type) {
  522. $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
  523. }
  524. $line = $prefix.$line;
  525. $line .= str_repeat(' ', max($this->lineLength - Helper::width(Helper::removeDecoration($this->getFormatter(), $line)), 0));
  526. if ($style) {
  527. $line = sprintf('<%s>%s</>', $style, $line);
  528. }
  529. }
  530. return $lines;
  531. }
  532. }