Debian Codegraph @

vendor/symfony/console/Style/SymfonyStyle.php

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