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