SymfonyStyle.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. private SymfonyQuestionHelper $questionHelper;
  39. private ProgressBar $progressBar;
  40. private int $lineLength;
  41. private TrimmedBufferOutput $bufferedOutput;
  42. public function __construct(
  43. private InputInterface $input,
  44. private OutputInterface $output,
  45. ) {
  46. $this->bufferedOutput = new TrimmedBufferOutput(\DIRECTORY_SEPARATOR === '\\' ? 4 : 2, $output->getVerbosity(), false, clone $output->getFormatter());
  47. // Windows cmd wraps lines as soon as the terminal width is reached, whether there are following chars or not.
  48. $width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH;
  49. $this->lineLength = min($width - (int) (\DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
  50. parent::__construct($output);
  51. }
  52. /**
  53. * Formats a message as a block of text.
  54. */
  55. public function block(string|array $messages, ?string $type = null, ?string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = true): void
  56. {
  57. $messages = \is_array($messages) ? array_values($messages) : [$messages];
  58. $this->autoPrependBlock();
  59. $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, $escape));
  60. $this->newLine();
  61. }
  62. public function title(string $message): void
  63. {
  64. $this->autoPrependBlock();
  65. $this->writeln([
  66. \sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
  67. \sprintf('<comment>%s</>', str_repeat('=', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))),
  68. ]);
  69. $this->newLine();
  70. }
  71. public function section(string $message): void
  72. {
  73. $this->autoPrependBlock();
  74. $this->writeln([
  75. \sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
  76. \sprintf('<comment>%s</>', str_repeat('-', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))),
  77. ]);
  78. $this->newLine();
  79. }
  80. public function listing(array $elements): void
  81. {
  82. $this->autoPrependText();
  83. $elements = array_map(fn ($element) => \sprintf(' * %s', $element), $elements);
  84. $this->writeln($elements);
  85. $this->newLine();
  86. }
  87. public function text(string|array $message): void
  88. {
  89. $this->autoPrependText();
  90. $messages = \is_array($message) ? array_values($message) : [$message];
  91. foreach ($messages as $message) {
  92. $this->writeln(\sprintf(' %s', $message));
  93. }
  94. }
  95. /**
  96. * Formats a command comment.
  97. */
  98. public function comment(string|array $message): void
  99. {
  100. $this->block($message, null, null, '<fg=default;bg=default> // </>', false, false);
  101. }
  102. public function success(string|array $message): void
  103. {
  104. $this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
  105. }
  106. public function error(string|array $message): void
  107. {
  108. $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
  109. }
  110. public function warning(string|array $message): void
  111. {
  112. $this->block($message, 'WARNING', 'fg=black;bg=yellow', ' ', true);
  113. }
  114. public function note(string|array $message): void
  115. {
  116. $this->block($message, 'NOTE', 'fg=yellow', ' ! ');
  117. }
  118. /**
  119. * Formats an info message.
  120. */
  121. public function info(string|array $message): void
  122. {
  123. $this->block($message, 'INFO', 'fg=green', ' ', true);
  124. }
  125. public function caution(string|array $message): void
  126. {
  127. $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
  128. }
  129. public function table(array $headers, array $rows): void
  130. {
  131. $this->createTable()
  132. ->setHeaders($headers)
  133. ->setRows($rows)
  134. ->render()
  135. ;
  136. $this->newLine();
  137. }
  138. /**
  139. * Formats a horizontal table.
  140. */
  141. public function horizontalTable(array $headers, array $rows): void
  142. {
  143. $this->createTable()
  144. ->setHorizontal(true)
  145. ->setHeaders($headers)
  146. ->setRows($rows)
  147. ->render()
  148. ;
  149. $this->newLine();
  150. }
  151. /**
  152. * Formats a list of key/value horizontally.
  153. *
  154. * Each row can be one of:
  155. * * 'A title'
  156. * * ['key' => 'value']
  157. * * new TableSeparator()
  158. */
  159. public function definitionList(string|array|TableSeparator ...$list): void
  160. {
  161. $headers = [];
  162. $row = [];
  163. foreach ($list as $value) {
  164. if ($value instanceof TableSeparator) {
  165. $headers[] = $value;
  166. $row[] = $value;
  167. continue;
  168. }
  169. if (\is_string($value)) {
  170. $headers[] = new TableCell($value, ['colspan' => 2]);
  171. $row[] = null;
  172. continue;
  173. }
  174. if (!\is_array($value)) {
  175. throw new InvalidArgumentException('Value should be an array, string, or an instance of TableSeparator.');
  176. }
  177. $headers[] = key($value);
  178. $row[] = current($value);
  179. }
  180. $this->horizontalTable($headers, [$row]);
  181. }
  182. public function ask(string $question, ?string $default = null, ?callable $validator = null): mixed
  183. {
  184. $question = new Question($question, $default);
  185. $question->setValidator($validator);
  186. return $this->askQuestion($question);
  187. }
  188. public function askHidden(string $question, ?callable $validator = null): mixed
  189. {
  190. $question = new Question($question);
  191. $question->setHidden(true);
  192. $question->setValidator($validator);
  193. return $this->askQuestion($question);
  194. }
  195. public function confirm(string $question, bool $default = true): bool
  196. {
  197. return $this->askQuestion(new ConfirmationQuestion($question, $default));
  198. }
  199. public function choice(string $question, array $choices, mixed $default = null, bool $multiSelect = false): mixed
  200. {
  201. if (null !== $default) {
  202. $values = array_flip($choices);
  203. $default = $values[$default] ?? $default;
  204. }
  205. $questionChoice = new ChoiceQuestion($question, $choices, $default);
  206. $questionChoice->setMultiselect($multiSelect);
  207. return $this->askQuestion($questionChoice);
  208. }
  209. public function progressStart(int $max = 0): void
  210. {
  211. $this->progressBar = $this->createProgressBar($max);
  212. $this->progressBar->start();
  213. }
  214. public function progressAdvance(int $step = 1): void
  215. {
  216. $this->getProgressBar()->advance($step);
  217. }
  218. public function progressFinish(): void
  219. {
  220. $this->getProgressBar()->finish();
  221. $this->newLine(2);
  222. unset($this->progressBar);
  223. }
  224. public function createProgressBar(int $max = 0): ProgressBar
  225. {
  226. $progressBar = parent::createProgressBar($max);
  227. if ('\\' !== \DIRECTORY_SEPARATOR || 'Hyper' === getenv('TERM_PROGRAM')) {
  228. $progressBar->setEmptyBarCharacter('░'); // light shade character \u2591
  229. $progressBar->setProgressCharacter('');
  230. $progressBar->setBarCharacter('▓'); // dark shade character \u2593
  231. }
  232. return $progressBar;
  233. }
  234. /**
  235. * @see ProgressBar::iterate()
  236. *
  237. * @template TKey
  238. * @template TValue
  239. *
  240. * @param iterable<TKey, TValue> $iterable
  241. * @param int|null $max Number of steps to complete the bar (0 if indeterminate), if null it will be inferred from $iterable
  242. *
  243. * @return iterable<TKey, TValue>
  244. */
  245. public function progressIterate(iterable $iterable, ?int $max = null): iterable
  246. {
  247. yield from $this->createProgressBar()->iterate($iterable, $max);
  248. $this->newLine(2);
  249. }
  250. public function askQuestion(Question $question): mixed
  251. {
  252. if ($this->input->isInteractive()) {
  253. $this->autoPrependBlock();
  254. }
  255. $this->questionHelper ??= new SymfonyQuestionHelper();
  256. $answer = $this->questionHelper->ask($this->input, $this, $question);
  257. if ($this->input->isInteractive()) {
  258. if ($this->output instanceof ConsoleSectionOutput) {
  259. // add the new line of the `return` to submit the input to ConsoleSectionOutput, because ConsoleSectionOutput is holding all it's lines.
  260. // this is relevant when a `ConsoleSectionOutput::clear` is called.
  261. $this->output->addNewLineOfInputSubmit();
  262. }
  263. $this->newLine();
  264. $this->bufferedOutput->write("\n");
  265. }
  266. return $answer;
  267. }
  268. public function writeln(string|iterable $messages, int $type = self::OUTPUT_NORMAL): void
  269. {
  270. if (!is_iterable($messages)) {
  271. $messages = [$messages];
  272. }
  273. foreach ($messages as $message) {
  274. parent::writeln($message, $type);
  275. $this->writeBuffer($message, true, $type);
  276. }
  277. }
  278. public function write(string|iterable $messages, bool $newline = false, int $type = self::OUTPUT_NORMAL): void
  279. {
  280. if (!is_iterable($messages)) {
  281. $messages = [$messages];
  282. }
  283. foreach ($messages as $message) {
  284. parent::write($message, $newline, $type);
  285. $this->writeBuffer($message, $newline, $type);
  286. }
  287. }
  288. public function newLine(int $count = 1): void
  289. {
  290. parent::newLine($count);
  291. $this->bufferedOutput->write(str_repeat("\n", $count));
  292. }
  293. /**
  294. * Returns a new instance which makes use of stderr if available.
  295. */
  296. public function getErrorStyle(): self
  297. {
  298. return new self($this->input, $this->getErrorOutput());
  299. }
  300. public function createTable(): Table
  301. {
  302. $output = $this->output instanceof ConsoleOutputInterface ? $this->output->section() : $this->output;
  303. $style = clone Table::getStyleDefinition('symfony-style-guide');
  304. $style->setCellHeaderFormat('<info>%s</info>');
  305. return (new Table($output))->setStyle($style);
  306. }
  307. private function getProgressBar(): ProgressBar
  308. {
  309. return $this->progressBar
  310. ?? throw new RuntimeException('The ProgressBar is not started.');
  311. }
  312. private function autoPrependBlock(): void
  313. {
  314. $chars = substr(str_replace(\PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
  315. if (!isset($chars[0])) {
  316. $this->newLine(); // empty history, so we should start with a new line.
  317. return;
  318. }
  319. // Prepend new line for each non LF chars (This means no blank line was output before)
  320. $this->newLine(2 - substr_count($chars, "\n"));
  321. }
  322. private function autoPrependText(): void
  323. {
  324. $fetched = $this->bufferedOutput->fetch();
  325. // Prepend new line if last char isn't EOL:
  326. if ($fetched && !str_ends_with($fetched, "\n")) {
  327. $this->newLine();
  328. }
  329. }
  330. private function writeBuffer(string $message, bool $newLine, int $type): void
  331. {
  332. // We need to know if the last chars are PHP_EOL
  333. $this->bufferedOutput->write($message, $newLine, $type);
  334. }
  335. private function createBlock(iterable $messages, ?string $type = null, ?string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = false): array
  336. {
  337. $indentLength = 0;
  338. $prefixLength = Helper::width(Helper::removeDecoration($this->getFormatter(), $prefix));
  339. $lines = [];
  340. if (null !== $type) {
  341. $type = \sprintf('[%s] ', $type);
  342. $indentLength = Helper::width($type);
  343. $lineIndentation = str_repeat(' ', $indentLength);
  344. }
  345. // wrap and add newlines for each element
  346. $outputWrapper = new OutputWrapper();
  347. foreach ($messages as $key => $message) {
  348. if ($escape) {
  349. $message = OutputFormatter::escape($message);
  350. }
  351. $lines = array_merge(
  352. $lines,
  353. explode(\PHP_EOL, $outputWrapper->wrap(
  354. $message,
  355. $this->lineLength - $prefixLength - $indentLength,
  356. \PHP_EOL
  357. ))
  358. );
  359. if (\count($messages) > 1 && $key < \count($messages) - 1) {
  360. $lines[] = '';
  361. }
  362. }
  363. $firstLineIndex = 0;
  364. if ($padding && $this->isDecorated()) {
  365. $firstLineIndex = 1;
  366. array_unshift($lines, '');
  367. $lines[] = '';
  368. }
  369. foreach ($lines as $i => &$line) {
  370. if (null !== $type) {
  371. $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
  372. }
  373. $line = $prefix.$line;
  374. $line .= str_repeat(' ', max($this->lineLength - Helper::width(Helper::removeDecoration($this->getFormatter(), $line)), 0));
  375. if ($style) {
  376. $line = \sprintf('<%s>%s</>', $style, $line);
  377. }
  378. }
  379. return $lines;
  380. }
  381. }