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;
43 public function __construct(InputInterface $input, OutputInterface $output)
45 $this->input = $input;
46 $this->bufferedOutput = new BufferedOutput($output->getVerbosity(), false, clone $output->getFormatter());
47 // Windows cmd wraps lines as soon as the terminal width is reached, whether there are following chars or not.
48 $width = (new Terminal())->getWidth() ?: self::MAX_LINE_LENGTH;
49 $this->lineLength = min($width - (int) (\DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
51 parent::__construct($output);
55 * Formats a message as a block of text.
57 * @param string|array $messages The message to write in the block
58 * @param string|null $type The block type (added in [] on first line)
59 * @param string|null $style The style to apply to the whole block
60 * @param string $prefix The prefix for the block
61 * @param bool $padding Whether to add vertical padding
62 * @param bool $escape Whether to escape the message
64 public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = true)
66 $messages = \is_array($messages) ? array_values($messages) : array($messages);
68 $this->autoPrependBlock();
69 $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, $escape));
76 public function title($message)
78 $this->autoPrependBlock();
80 sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
81 sprintf('<comment>%s</>', str_repeat('=', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
89 public function section($message)
91 $this->autoPrependBlock();
93 sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
94 sprintf('<comment>%s</>', str_repeat('-', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
102 public function listing(array $elements)
104 $this->autoPrependText();
105 $elements = array_map(function ($element) {
106 return sprintf(' * %s', $element);
109 $this->writeln($elements);
116 public function text($message)
118 $this->autoPrependText();
120 $messages = \is_array($message) ? array_values($message) : array($message);
121 foreach ($messages as $message) {
122 $this->writeln(sprintf(' %s', $message));
127 * Formats a command comment.
129 * @param string|array $message
131 public function comment($message)
133 $this->block($message, null, null, '<fg=default;bg=default> // </>', false, false);
139 public function success($message)
141 $this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
147 public function error($message)
149 $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
155 public function warning($message)
157 $this->block($message, 'WARNING', 'fg=white;bg=red', ' ', true);
163 public function note($message)
165 $this->block($message, 'NOTE', 'fg=yellow', ' ! ');
171 public function caution($message)
173 $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
179 public function table(array $headers, array $rows)
181 $style = clone Table::getStyleDefinition('symfony-style-guide');
182 $style->setCellHeaderFormat('<info>%s</info>');
184 $table = new Table($this);
185 $table->setHeaders($headers);
186 $table->setRows($rows);
187 $table->setStyle($style);
196 public function ask($question, $default = null, $validator = null)
198 $question = new Question($question, $default);
199 $question->setValidator($validator);
201 return $this->askQuestion($question);
207 public function askHidden($question, $validator = null)
209 $question = new Question($question);
211 $question->setHidden(true);
212 $question->setValidator($validator);
214 return $this->askQuestion($question);
220 public function confirm($question, $default = true)
222 return $this->askQuestion(new ConfirmationQuestion($question, $default));
228 public function choice($question, array $choices, $default = null)
230 if (null !== $default) {
231 $values = array_flip($choices);
232 $default = $values[$default];
235 return $this->askQuestion(new ChoiceQuestion($question, $choices, $default));
241 public function progressStart($max = 0)
243 $this->progressBar = $this->createProgressBar($max);
244 $this->progressBar->start();
250 public function progressAdvance($step = 1)
252 $this->getProgressBar()->advance($step);
258 public function progressFinish()
260 $this->getProgressBar()->finish();
262 $this->progressBar = null;
268 public function createProgressBar($max = 0)
270 $progressBar = parent::createProgressBar($max);
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
284 public function askQuestion(Question $question)
286 if ($this->input->isInteractive()) {
287 $this->autoPrependBlock();
290 if (!$this->questionHelper) {
291 $this->questionHelper = new SymfonyQuestionHelper();
294 $answer = $this->questionHelper->ask($this->input, $this, $question);
296 if ($this->input->isInteractive()) {
298 $this->bufferedOutput->write("\n");
307 public function writeln($messages, $type = self::OUTPUT_NORMAL)
309 parent::writeln($messages, $type);
310 $this->bufferedOutput->writeln($this->reduceBuffer($messages), $type);
316 public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
318 parent::write($messages, $newline, $type);
319 $this->bufferedOutput->write($this->reduceBuffer($messages), $newline, $type);
325 public function newLine($count = 1)
327 parent::newLine($count);
328 $this->bufferedOutput->write(str_repeat("\n", $count));
332 * Returns a new instance which makes use of stderr if available.
336 public function getErrorStyle()
338 return new self($this->input, $this->getErrorOutput());
342 * @return ProgressBar
344 private function getProgressBar()
346 if (!$this->progressBar) {
347 throw new RuntimeException('The ProgressBar is not started.');
350 return $this->progressBar;
353 private function autoPrependBlock()
355 $chars = substr(str_replace(PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
357 if (!isset($chars[0])) {
358 return $this->newLine(); //empty history, so we should start with a new line.
360 //Prepend new line for each non LF chars (This means no blank line was output before)
361 $this->newLine(2 - substr_count($chars, "\n"));
364 private function autoPrependText()
366 $fetched = $this->bufferedOutput->fetch();
367 //Prepend new line if last char isn't EOL:
368 if ("\n" !== substr($fetched, -1)) {
373 private function reduceBuffer($messages)
375 // We need to know if the two last chars are PHP_EOL
376 // Preserve the last 4 chars inserted (PHP_EOL on windows is two chars) in the history buffer
377 return array_map(function ($value) {
378 return substr($value, -4);
379 }, array_merge(array($this->bufferedOutput->fetch()), (array) $messages));
382 private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false)
385 $prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix);
388 if (null !== $type) {
389 $type = sprintf('[%s] ', $type);
390 $indentLength = \strlen($type);
391 $lineIndentation = str_repeat(' ', $indentLength);
394 // wrap and add newlines for each element
395 foreach ($messages as $key => $message) {
397 $message = OutputFormatter::escape($message);
400 $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, PHP_EOL, true)));
402 if (\count($messages) > 1 && $key < \count($messages) - 1) {
408 if ($padding && $this->isDecorated()) {
410 array_unshift($lines, '');
414 foreach ($lines as $i => &$line) {
415 if (null !== $type) {
416 $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
419 $line = $prefix.$line;
420 $line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
423 $line = sprintf('<%s>%s</>', $style, $line);