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\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;
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 $this->lineLength = min($this->getTerminalWidth() - (int) (DIRECTORY_SEPARATOR === '\\'), self::MAX_LINE_LENGTH);
54 parent::__construct($output);
58 * Formats a message as a block of text.
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
66 public function block($messages, $type = null, $style = null, $prefix = ' ', $padding = false)
68 $messages = is_array($messages) ? array_values($messages) : array($messages);
70 $this->autoPrependBlock();
71 $this->writeln($this->createBlock($messages, $type, $style, $prefix, $padding, true));
78 public function title($message)
80 $this->autoPrependBlock();
82 sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
83 sprintf('<comment>%s</>', str_repeat('=', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
91 public function section($message)
93 $this->autoPrependBlock();
95 sprintf('<comment>%s</>', OutputFormatter::escapeTrailingBackslash($message)),
96 sprintf('<comment>%s</>', str_repeat('-', Helper::strlenWithoutDecoration($this->getFormatter(), $message))),
104 public function listing(array $elements)
106 $this->autoPrependText();
107 $elements = array_map(function ($element) {
108 return sprintf(' * %s', $element);
111 $this->writeln($elements);
118 public function text($message)
120 $this->autoPrependText();
122 $messages = is_array($message) ? array_values($message) : array($message);
123 foreach ($messages as $message) {
124 $this->writeln(sprintf(' %s', $message));
129 * Formats a command comment.
131 * @param string|array $message
133 public function comment($message)
135 $messages = is_array($message) ? array_values($message) : array($message);
137 $this->autoPrependBlock();
138 $this->writeln($this->createBlock($messages, null, null, '<fg=default;bg=default> // </>'));
145 public function success($message)
147 $this->block($message, 'OK', 'fg=black;bg=green', ' ', true);
153 public function error($message)
155 $this->block($message, 'ERROR', 'fg=white;bg=red', ' ', true);
161 public function warning($message)
163 $this->block($message, 'WARNING', 'fg=white;bg=red', ' ', true);
169 public function note($message)
171 $this->block($message, 'NOTE', 'fg=yellow', ' ! ');
177 public function caution($message)
179 $this->block($message, 'CAUTION', 'fg=white;bg=red', ' ! ', true);
185 public function table(array $headers, array $rows)
187 $style = clone Table::getStyleDefinition('symfony-style-guide');
188 $style->setCellHeaderFormat('<info>%s</info>');
190 $table = new Table($this);
191 $table->setHeaders($headers);
192 $table->setRows($rows);
193 $table->setStyle($style);
202 public function ask($question, $default = null, $validator = null)
204 $question = new Question($question, $default);
205 $question->setValidator($validator);
207 return $this->askQuestion($question);
213 public function askHidden($question, $validator = null)
215 $question = new Question($question);
217 $question->setHidden(true);
218 $question->setValidator($validator);
220 return $this->askQuestion($question);
226 public function confirm($question, $default = true)
228 return $this->askQuestion(new ConfirmationQuestion($question, $default));
234 public function choice($question, array $choices, $default = null)
236 if (null !== $default) {
237 $values = array_flip($choices);
238 $default = $values[$default];
241 return $this->askQuestion(new ChoiceQuestion($question, $choices, $default));
247 public function progressStart($max = 0)
249 $this->progressBar = $this->createProgressBar($max);
250 $this->progressBar->start();
256 public function progressAdvance($step = 1)
258 $this->getProgressBar()->advance($step);
264 public function progressFinish()
266 $this->getProgressBar()->finish();
268 $this->progressBar = null;
274 public function createProgressBar($max = 0)
276 $progressBar = parent::createProgressBar($max);
278 if ('\\' !== DIRECTORY_SEPARATOR) {
279 $progressBar->setEmptyBarCharacter('░'); // light shade character \u2591
280 $progressBar->setProgressCharacter('');
281 $progressBar->setBarCharacter('▓'); // dark shade character \u2593
288 * @param Question $question
292 public function askQuestion(Question $question)
294 if ($this->input->isInteractive()) {
295 $this->autoPrependBlock();
298 if (!$this->questionHelper) {
299 $this->questionHelper = new SymfonyQuestionHelper();
302 $answer = $this->questionHelper->ask($this->input, $this, $question);
304 if ($this->input->isInteractive()) {
306 $this->bufferedOutput->write("\n");
315 public function writeln($messages, $type = self::OUTPUT_NORMAL)
317 parent::writeln($messages, $type);
318 $this->bufferedOutput->writeln($this->reduceBuffer($messages), $type);
324 public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
326 parent::write($messages, $newline, $type);
327 $this->bufferedOutput->write($this->reduceBuffer($messages), $newline, $type);
333 public function newLine($count = 1)
335 parent::newLine($count);
336 $this->bufferedOutput->write(str_repeat("\n", $count));
340 * @return ProgressBar
342 private function getProgressBar()
344 if (!$this->progressBar) {
345 throw new RuntimeException('The ProgressBar is not started.');
348 return $this->progressBar;
351 private function getTerminalWidth()
353 $application = new Application();
354 $dimensions = $application->getTerminalDimensions();
356 return $dimensions[0] ?: self::MAX_LINE_LENGTH;
359 private function autoPrependBlock()
361 $chars = substr(str_replace(PHP_EOL, "\n", $this->bufferedOutput->fetch()), -2);
363 if (!isset($chars[0])) {
364 return $this->newLine(); //empty history, so we should start with a new line.
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"));
370 private function autoPrependText()
372 $fetched = $this->bufferedOutput->fetch();
373 //Prepend new line if last char isn't EOL:
374 if ("\n" !== substr($fetched, -1)) {
379 private function reduceBuffer($messages)
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));
388 private function createBlock($messages, $type = null, $style = null, $prefix = ' ', $padding = false, $escape = false)
391 $prefixLength = Helper::strlenWithoutDecoration($this->getFormatter(), $prefix);
394 if (null !== $type) {
395 $type = sprintf('[%s] ', $type);
396 $indentLength = strlen($type);
397 $lineIndentation = str_repeat(' ', $indentLength);
400 // wrap and add newlines for each element
401 foreach ($messages as $key => $message) {
403 $message = OutputFormatter::escape($message);
406 $lines = array_merge($lines, explode(PHP_EOL, wordwrap($message, $this->lineLength - $prefixLength - $indentLength, PHP_EOL, true)));
408 if (count($messages) > 1 && $key < count($messages) - 1) {
414 if ($padding && $this->isDecorated()) {
416 array_unshift($lines, '');
420 foreach ($lines as $i => &$line) {
421 if (null !== $type) {
422 $line = $firstLineIndex === $i ? $type.$line : $lineIndentation.$line;
425 $line = $prefix.$line;
426 $line .= str_repeat(' ', $this->lineLength - Helper::strlenWithoutDecoration($this->getFormatter(), $line));
429 $line = sprintf('<%s>%s</>', $style, $line);