4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Style;
14 use Symfony\Component\Console\Exception\RuntimeException;
15 use Symfony\Component\Console\Formatter\OutputFormatter;
16 use Symfony\Component\Console\Helper\Helper;
17 use Symfony\Component\Console\Helper\ProgressBar;
18 use Symfony\Component\Console\Helper\SymfonyQuestionHelper;
19 use Symfony\Component\Console\Helper\Table;
20 use Symfony\Component\Console\Input\InputInterface;
21 use Symfony\Component\Console\Output\BufferedOutput;
22 use Symfony\Component\Console\Output\OutputInterface;
23 use Symfony\Component\Console\Question\ChoiceQuestion;
24 use Symfony\Component\Console\Question\ConfirmationQuestion;
25 use Symfony\Component\Console\Question\Question;
26 use Symfony\Component\Console\Terminal;
29 * Output decorator helpers for the Symfony Style Guide.
31 * @author Kevin Bond <kevinbond@gmail.com>
33 class SymfonyStyle extends OutputStyle
35 const MAX_LINE_LENGTH = 120;
38 private $questionHelper;
41 private $bufferedOutput;
44 * @param InputInterface $input
45 * @param OutputInterface $output
47 public function __construct(InputInterface $input, OutputInterface $output)
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 $width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH;
53 $this->lineLength = min($width - (int) (DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
55 parent::__construct($output);
59 * Formats a message as a block of text.
61 * @param string|array $messages The message to write in the block
62 * @param string|null $type The block type (added in [] on first line)
63 * @param string|null $style The style to apply to the whole block
64 * @param string $prefix The prefix for the block
65 * @param bool $padding Whether to add vertical padding
67 public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false)
69 $messages = is_array($messages) ? array_values($messages) : array($messages);
71 $this->autoPrependBlock();
72 $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, true));
79 public function title($message)
81 $this->autoPrependBlock();
83 sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
84 sprintf('<comment>%s</>', str_repeat('=', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
92 public function section($message)
94 $this->autoPrependBlock();
96 sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
97 sprintf('<comment>%s</>', str_repeat('-', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
105 public function listing(array $elements)
107 $this->autoPrependText();
108 $elements = array_map(function ($element) {
109 return sprintf(' * %s', $element);
112 $this->writeln($elements);
119 public function text($message)
121 $this->autoPrependText();
123 $messages = is_array($message) ? array_values($message) : array($message);
124 foreach ($messages as $message) {
125 $this->writeln(sprintf(' %s', $message));
130 * Formats a command comment.
132 * @param string|array $message
134 public function comment($message)
136 $messages = is_array($message) ? array_values($message) : array($message);
138 $this->autoPrependBlock();
139 $this->writeln($this->createBlock($messages, null, null, '<fg=default;bg=default> // </>'));
146 public function success($message)
148 $this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
154 public function error($message)
156 $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
162 public function warning($message)
164 $this->block($message, 'WARNING', 'fg=white;bg=red', ' ', true);
170 public function note($message)
172 $this->block($message, 'NOTE', 'fg=yellow', ' ! ');
178 public function caution($message)
180 $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
186 public function table(array $headers, array $rows)
188 $style = clone Table::getStyleDefinition('symfony-style-guide');
189 $style->setCellHeaderFormat('<info>%s</info>');
191 $table = new Table($this);
192 $table->setHeaders($headers);
193 $table->setRows($rows);
194 $table->setStyle($style);
203 public function ask($question, $default = null, $validator = null)
205 $question = new Question($question, $default);
206 $question->setValidator($validator);
208 return $this->askQuestion($question);
214 public function askHidden($question, $validator = null)
216 $question = new Question($question);
218 $question->setHidden(true);
219 $question->setValidator($validator);
221 return $this->askQuestion($question);
227 public function confirm($question, $default = true)
229 return $this->askQuestion(new ConfirmationQuestion($question, $default));
235 public function choice($question, array $choices, $default = null)
237 if (null !== $default) {
238 $values = array_flip($choices);
239 $default = $values[$default];
242 return $this->askQuestion(new ChoiceQuestion($question, $choices, $default));
248 public function progressStart($max = 0)
250 $this->progressBar = $this->createProgressBar($max);
251 $this->progressBar->start();
257 public function progressAdvance($step = 1)
259 $this->getProgressBar()->advance($step);
265 public function progressFinish()
267 $this->getProgressBar()->finish();
269 $this->progressBar = null;
275 public function createProgressBar($max = 0)
277 $progressBar = parent::createProgressBar($max);
279 if ('\\' !== DIRECTORY_SEPARATOR) {
280 $progressBar->setEmptyBarCharacter('░'); // light shade character \u2591
281 $progressBar->setProgressCharacter('');
282 $progressBar->setBarCharacter('▓'); // dark shade character \u2593
289 * @param Question $question
293 public function askQuestion(Question $question)
295 if ($this->input->isInteractive()) {
296 $this->autoPrependBlock();
299 if (!$this->questionHelper) {
300 $this->questionHelper = new SymfonyQuestionHelper();
303 $answer = $this->questionHelper->ask($this->input, $this, $question);
305 if ($this->input->isInteractive()) {
307 $this->bufferedOutput->write("\n");
316 public function writeln($messages, $type = self::OUTPUT_NORMAL)
318 parent::writeln($messages, $type);
319 $this->bufferedOutput->writeln($this->reduceBuffer($messages), $type);
325 public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
327 parent::write($messages, $newline, $type);
328 $this->bufferedOutput->write($this->reduceBuffer($messages), $newline, $type);
334 public function newLine($count = 1)
336 parent::newLine($count);
337 $this->bufferedOutput->write(str_repeat("\n", $count));
341 * @return ProgressBar
343 private function getProgressBar()
345 if (!$this->progressBar) {
346 throw new RuntimeException('The ProgressBar is not started.');
349 return $this->progressBar;
352 private function autoPrependBlock()
354 $chars = substr(str_replace(PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
356 if (!isset($chars[0])) {
357 return $this->newLine(); //empty history, so we should start with a new line.
359 //Prepend new line for each non LF chars (This means no blank line was output before)
360 $this->newLine(2 - substr_count($chars, "\n"));
363 private function autoPrependText()
365 $fetched = $this->bufferedOutput->fetch();
366 //Prepend new line if last char isn't EOL:
367 if ("\n" !== substr($fetched, -1)) {
372 private function reduceBuffer($messages)
374 // We need to know if the two last chars are PHP_EOL
375 // Preserve the last 4 chars inserted (PHP_EOL on windows is two chars) in the history buffer
376 return array_map(function ($value) {
377 return substr($value, -4);
378 }, array_merge(array($this->bufferedOutput->fetch()), (array) $messages));
381 private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false)
384 $prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix);
387 if (null !== $type) {
388 $type = sprintf('[%s] ', $type);
389 $indentLength = strlen($type);
390 $lineIndentation = str_repeat(' ', $indentLength);
393 // wrap and add newlines for each element
394 foreach ($messages as $key => $message) {
396 $message = OutputFormatter::escape($message);
399 $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, PHP_EOL, true)));
401 if (count($messages) > 1 && $key < count($messages) - 1) {
407 if ($padding && $this->isDecorated()) {
409 array_unshift($lines, '');
413 foreach ($lines as $i => &$line) {
414 if (null !== $type) {
415 $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
418 $line = $prefix.$line;
419 $line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
422 $line = sprintf('<%s>%s</>', $style, $line);