Subversion-Projekte lars-tiefland.laravel_shop

Revision

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