Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 1
<?php
2
 
3
/*
4
 * This file is part of the Symfony package.
5
 *
6
 * (c) Fabien Potencier <fabien@symfony.com>
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\Input\InputInterface;
25
use Symfony\Component\Console\Output\ConsoleOutputInterface;
688 lars 26
use Symfony\Component\Console\Output\ConsoleSectionOutput;
148 lars 27
use Symfony\Component\Console\Output\OutputInterface;
28
use Symfony\Component\Console\Output\TrimmedBufferOutput;
29
use Symfony\Component\Console\Question\ChoiceQuestion;
30
use Symfony\Component\Console\Question\ConfirmationQuestion;
31
use Symfony\Component\Console\Question\Question;
32
use Symfony\Component\Console\Terminal;
33
 
34
/**
35
 * Output decorator helpers for the Symfony Style Guide.
36
 *
37
 * @author Kevin Bond <kevinbond@gmail.com>
38
 */
39
class SymfonyStyle extends OutputStyle
40
{
41
    public const MAX_LINE_LENGTH = 120;
42
 
43
    private InputInterface $input;
44
    private OutputInterface $output;
45
    private SymfonyQuestionHelper $questionHelper;
46
    private ProgressBar $progressBar;
47
    private int $lineLength;
48
    private TrimmedBufferOutput $bufferedOutput;
49
 
50
    public function __construct(InputInterface $input, OutputInterface $output)
51
    {
52
        $this->input = $input;
53
        $this->bufferedOutput = new TrimmedBufferOutput(\DIRECTORY_SEPARATOR === '\\' ? 4 : 2, $output->getVerbosity(), false, clone $output->getFormatter());
54
        // Windows cmd wraps lines as soon as the terminal width is reached, whether there are following chars or not.
55
        $width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH;
56
        $this->lineLength = min($width - (int) (\DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
57
 
58
        parent::__construct($this->output = $output);
59
    }
60
 
61
    /**
62
     * Formats a message as a block of text.
63
     */
64
    public function block(string|array $messages, string $type = null, string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = true)
65
    {
66
        $messages = \is_array($messages) ? array_values($messages) : [$messages];
67
 
68
        $this->autoPrependBlock();
69
        $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, $escape));
70
        $this->newLine();
71
    }
72
 
73
    public function title(string $message)
74
    {
75
        $this->autoPrependBlock();
76
        $this->writeln([
77
            sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
78
            sprintf('<comment>%s</>', str_repeat('=', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))),
79
        ]);
80
        $this->newLine();
81
    }
82
 
83
    public function section(string $message)
84
    {
85
        $this->autoPrependBlock();
86
        $this->writeln([
87
            sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
88
            sprintf('<comment>%s</>', str_repeat('-', Helper::width(Helper::removeDecoration($this->getFormatter(), $message)))),
89
        ]);
90
        $this->newLine();
91
    }
92
 
93
    public function listing(array $elements)
94
    {
95
        $this->autoPrependText();
96
        $elements = array_map(function ($element) {
97
            return sprintf(' * %s', $element);
98
        }, $elements);
99
 
100
        $this->writeln($elements);
101
        $this->newLine();
102
    }
103
 
104
    public function text(string|array $message)
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)
118
    {
119
        $this->block($message, null, null, '<fg=default;bg=default> // </>', false, false);
120
    }
121
 
122
    public function success(string|array $message)
123
    {
124
        $this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
125
    }
126
 
127
    public function error(string|array $message)
128
    {
129
        $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
130
    }
131
 
132
    public function warning(string|array $message)
133
    {
134
        $this->block($message, 'WARNING', 'fg=black;bg=yellow', ' ', true);
135
    }
136
 
137
    public function note(string|array $message)
138
    {
139
        $this->block($message, 'NOTE', 'fg=yellow', ' ! ');
140
    }
141
 
142
    /**
143
     * Formats an info message.
144
     */
145
    public function info(string|array $message)
146
    {
147
        $this->block($message, 'INFO', 'fg=green', ' ', true);
148
    }
149
 
150
    public function caution(string|array $message)
151
    {
152
        $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
153
    }
154
 
155
    public function table(array $headers, array $rows)
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)
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)
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)
251
    {
252
        $this->progressBar = $this->createProgressBar($max);
253
        $this->progressBar->start();
254
    }
255
 
256
    public function progressAdvance(int $step = 1)
257
    {
258
        $this->getProgressBar()->advance($step);
259
    }
260
 
261
    public function progressFinish()
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
    public function progressIterate(iterable $iterable, int $max = null): iterable
285
    {
286
        yield from $this->createProgressBar()->iterate($iterable, $max);
287
 
288
        $this->newLine(2);
289
    }
290
 
291
    public function askQuestion(Question $question): mixed
292
    {
293
        if ($this->input->isInteractive()) {
294
            $this->autoPrependBlock();
295
        }
296
 
297
        $this->questionHelper ??= new SymfonyQuestionHelper();
298
 
299
        $answer = $this->questionHelper->ask($this->input, $this, $question);
300
 
301
        if ($this->input->isInteractive()) {
688 lars 302
            if ($this->output instanceof ConsoleSectionOutput) {
303
                // add the new line of the `return` to submit the input to ConsoleSectionOutput, because ConsoleSectionOutput is holding all it's lines.
304
                // this is relevant when a `ConsoleSectionOutput::clear` is called.
305
                $this->output->addNewLineOfInputSubmit();
306
            }
148 lars 307
            $this->newLine();
308
            $this->bufferedOutput->write("\n");
309
        }
310
 
311
        return $answer;
312
    }
313
 
314
    public function writeln(string|iterable $messages, int $type = self::OUTPUT_NORMAL)
315
    {
316
        if (!is_iterable($messages)) {
317
            $messages = [$messages];
318
        }
319
 
320
        foreach ($messages as $message) {
321
            parent::writeln($message, $type);
322
            $this->writeBuffer($message, true, $type);
323
        }
324
    }
325
 
326
    public function write(string|iterable $messages, bool $newline = false, int $type = self::OUTPUT_NORMAL)
327
    {
328
        if (!is_iterable($messages)) {
329
            $messages = [$messages];
330
        }
331
 
332
        foreach ($messages as $message) {
333
            parent::write($message, $newline, $type);
334
            $this->writeBuffer($message, $newline, $type);
335
        }
336
    }
337
 
338
    public function newLine(int $count = 1)
339
    {
340
        parent::newLine($count);
341
        $this->bufferedOutput->write(str_repeat("\n", $count));
342
    }
343
 
344
    /**
345
     * Returns a new instance which makes use of stderr if available.
346
     */
347
    public function getErrorStyle(): self
348
    {
349
        return new self($this->input, $this->getErrorOutput());
350
    }
351
 
352
    public function createTable(): Table
353
    {
354
        $output = $this->output instanceof ConsoleOutputInterface ? $this->output->section() : $this->output;
355
        $style = clone Table::getStyleDefinition('symfony-style-guide');
356
        $style->setCellHeaderFormat('<info>%s</info>');
357
 
358
        return (new Table($output))->setStyle($style);
359
    }
360
 
361
    private function getProgressBar(): ProgressBar
362
    {
363
        return $this->progressBar
364
            ?? throw new RuntimeException('The ProgressBar is not started.');
365
    }
366
 
367
    private function autoPrependBlock(): void
368
    {
369
        $chars = substr(str_replace(\PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
370
 
371
        if (!isset($chars[0])) {
372
            $this->newLine(); // empty history, so we should start with a new line.
373
 
374
            return;
375
        }
376
        // Prepend new line for each non LF chars (This means no blank line was output before)
377
        $this->newLine(2 - substr_count($chars, "\n"));
378
    }
379
 
380
    private function autoPrependText(): void
381
    {
382
        $fetched = $this->bufferedOutput->fetch();
383
        // Prepend new line if last char isn't EOL:
384
        if (!str_ends_with($fetched, "\n")) {
385
            $this->newLine();
386
        }
387
    }
388
 
389
    private function writeBuffer(string $message, bool $newLine, int $type): void
390
    {
391
        // We need to know if the last chars are PHP_EOL
392
        $this->bufferedOutput->write($message, $newLine, $type);
393
    }
394
 
395
    private function createBlock(iterable $messages, string $type = null, string $style = null, string $prefix = ' ', bool $padding = false, bool $escape = false): array
396
    {
397
        $indentLength = 0;
398
        $prefixLength = Helper::width(Helper::removeDecoration($this->getFormatter(), $prefix));
399
        $lines = [];
400
 
401
        if (null !== $type) {
402
            $type = sprintf('[%s] ', $type);
403
            $indentLength = Helper::width($type);
404
            $lineIndentation = str_repeat(' ', $indentLength);
405
        }
406
 
407
        // wrap and add newlines for each element
408
        $outputWrapper = new OutputWrapper();
409
        foreach ($messages as $key => $message) {
410
            if ($escape) {
411
                $message = OutputFormatter::escape($message);
412
            }
413
 
414
            $lines = array_merge(
415
                $lines,
416
                explode(\PHP_EOL, $outputWrapper->wrap(
417
                    $message,
418
                    $this->lineLength - $prefixLength - $indentLength,
419
                    \PHP_EOL
420
                ))
421
            );
422
 
423
            if (\count($messages) > 1 && $key < \count($messages) - 1) {
424
                $lines[] = '';
425
            }
426
        }
427
 
428
        $firstLineIndex = 0;
429
        if ($padding && $this->isDecorated()) {
430
            $firstLineIndex = 1;
431
            array_unshift($lines, '');
432
            $lines[] = '';
433
        }
434
 
435
        foreach ($lines as $i => &$line) {
436
            if (null !== $type) {
437
                $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
438
            }
439
 
440
            $line = $prefix.$line;
441
            $line .= str_repeat(' ', max($this->lineLength - Helper::width(Helper::removeDecoration($this->getFormatter(), $line)), 0));
442
 
443
            if ($style) {
444
                $line = sprintf('<%s>%s</>', $style, $line);
445
            }
446
        }
447
 
448
        return $lines;
449
    }
450
}