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\Helper;
14 use Symfony\Component\Console\Exception\LogicException;
15 use Symfony\Component\Console\Output\ConsoleOutputInterface;
16 use Symfony\Component\Console\Output\OutputInterface;
17 use Symfony\Component\Console\Terminal;
20 * The ProgressBar provides helpers to display progress output.
22 * @author Fabien Potencier <fabien@symfony.com>
23 * @author Chris Jones <leeked@gmail.com>
25 final class ProgressBar
27 private $barWidth = 28;
29 private $emptyBarChar = '-';
30 private $progressChar = '>';
32 private $internalFormat;
33 private $redrawFreq = 1;
39 private $percent = 0.0;
40 private $formatLineCount;
41 private $messages = array();
42 private $overwrite = true;
44 private $firstRun = true;
46 private static $formatters;
47 private static $formats;
50 * @param OutputInterface $output An OutputInterface instance
51 * @param int $max Maximum steps (0 if unknown)
53 public function __construct(OutputInterface $output, $max = 0)
55 if ($output instanceof ConsoleOutputInterface) {
56 $output = $output->getErrorOutput();
59 $this->output = $output;
60 $this->setMaxSteps($max);
61 $this->terminal = new Terminal();
63 if (!$this->output->isDecorated()) {
64 // disable overwrite when output does not support ANSI codes.
65 $this->overwrite = false;
67 // set a reasonable redraw frequency so output isn't flooded
68 $this->setRedrawFrequency($max / 10);
71 $this->startTime = time();
75 * Sets a placeholder formatter for a given name.
77 * This method also allow you to override an existing placeholder.
79 * @param string $name The placeholder name (including the delimiter char like %)
80 * @param callable $callable A PHP callable
82 public static function setPlaceholderFormatterDefinition($name, callable $callable)
84 if (!self::$formatters) {
85 self::$formatters = self::initPlaceholderFormatters();
88 self::$formatters[$name] = $callable;
92 * Gets the placeholder formatter for a given name.
94 * @param string $name The placeholder name (including the delimiter char like %)
96 * @return callable|null A PHP callable
98 public static function getPlaceholderFormatterDefinition($name)
100 if (!self::$formatters) {
101 self::$formatters = self::initPlaceholderFormatters();
104 return isset(self::$formatters[$name]) ? self::$formatters[$name] : null;
108 * Sets a format for a given name.
110 * This method also allow you to override an existing format.
112 * @param string $name The format name
113 * @param string $format A format string
115 public static function setFormatDefinition($name, $format)
117 if (!self::$formats) {
118 self::$formats = self::initFormats();
121 self::$formats[$name] = $format;
125 * Gets the format for a given name.
127 * @param string $name The format name
129 * @return string|null A format string
131 public static function getFormatDefinition($name)
133 if (!self::$formats) {
134 self::$formats = self::initFormats();
137 return isset(self::$formats[$name]) ? self::$formats[$name] : null;
141 * Associates a text with a named placeholder.
143 * The text is displayed when the progress bar is rendered but only
144 * when the corresponding placeholder is part of the custom format line
145 * (by wrapping the name with %).
147 * @param string $message The text to associate with the placeholder
148 * @param string $name The name of the placeholder
150 public function setMessage($message, $name = 'message')
152 $this->messages[$name] = $message;
155 public function getMessage($name = 'message')
157 return $this->messages[$name];
161 * Gets the progress bar start time.
163 * @return int The progress bar start time
165 public function getStartTime()
167 return $this->startTime;
171 * Gets the progress bar maximal steps.
173 * @return int The progress bar max steps
175 public function getMaxSteps()
181 * Gets the current step position.
183 * @return int The progress bar step
185 public function getProgress()
191 * Gets the progress bar step width.
193 * @return int The progress bar step width
195 private function getStepWidth()
197 return $this->stepWidth;
201 * Gets the current progress bar percent.
203 * @return float The current progress bar percent
205 public function getProgressPercent()
207 return $this->percent;
211 * Sets the progress bar width.
213 * @param int $size The progress bar size
215 public function setBarWidth($size)
217 $this->barWidth = max(1, (int) $size);
221 * Gets the progress bar width.
223 * @return int The progress bar size
225 public function getBarWidth()
227 return $this->barWidth;
231 * Sets the bar character.
233 * @param string $char A character
235 public function setBarCharacter($char)
237 $this->barChar = $char;
241 * Gets the bar character.
243 * @return string A character
245 public function getBarCharacter()
247 if (null === $this->barChar) {
248 return $this->max ? '=' : $this->emptyBarChar;
251 return $this->barChar;
255 * Sets the empty bar character.
257 * @param string $char A character
259 public function setEmptyBarCharacter($char)
261 $this->emptyBarChar = $char;
265 * Gets the empty bar character.
267 * @return string A character
269 public function getEmptyBarCharacter()
271 return $this->emptyBarChar;
275 * Sets the progress bar character.
277 * @param string $char A character
279 public function setProgressCharacter($char)
281 $this->progressChar = $char;
285 * Gets the progress bar character.
287 * @return string A character
289 public function getProgressCharacter()
291 return $this->progressChar;
295 * Sets the progress bar format.
297 * @param string $format The format
299 public function setFormat($format)
301 $this->format = null;
302 $this->internalFormat = $format;
306 * Sets the redraw frequency.
308 * @param int|float $freq The frequency in steps
310 public function setRedrawFrequency($freq)
312 $this->redrawFreq = max((int) $freq, 1);
316 * Starts the progress output.
318 * @param int|null $max Number of steps to complete the bar (0 if indeterminate), null to leave unchanged
320 public function start($max = null)
322 $this->startTime = time();
324 $this->percent = 0.0;
327 $this->setMaxSteps($max);
334 * Advances the progress output X steps.
336 * @param int $step Number of steps to advance
338 public function advance($step = 1)
340 $this->setProgress($this->step + $step);
344 * Sets whether to overwrite the progressbar, false for new line.
346 * @param bool $overwrite
348 public function setOverwrite($overwrite)
350 $this->overwrite = (bool) $overwrite;
354 * Sets the current progress.
356 * @param int $step The current progress
358 public function setProgress($step)
362 if ($this->max && $step > $this->max) {
364 } elseif ($step < 0) {
368 $prevPeriod = (int) ($this->step / $this->redrawFreq);
369 $currPeriod = (int) ($step / $this->redrawFreq);
371 $this->percent = $this->max ? (float) $this->step / $this->max : 0;
372 if ($prevPeriod !== $currPeriod || $this->max === $step) {
378 * Finishes the progress output.
380 public function finish()
383 $this->max = $this->step;
386 if ($this->step === $this->max && !$this->overwrite) {
387 // prevent double 100% output
391 $this->setProgress($this->max);
395 * Outputs the current progress string.
397 public function display()
399 if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
403 if (null === $this->format) {
404 $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
407 $this->overwrite($this->buildLine());
411 * Removes the progress bar from the current line.
413 * This is useful if you wish to write some output
414 * while a progress bar is running.
415 * Call display() to show the progress bar again.
417 public function clear()
419 if (!$this->overwrite) {
423 if (null === $this->format) {
424 $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
427 $this->overwrite('');
431 * Sets the progress bar format.
433 * @param string $format The format
435 private function setRealFormat($format)
437 // try to use the _nomax variant if available
438 if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) {
439 $this->format = self::getFormatDefinition($format.'_nomax');
440 } elseif (null !== self::getFormatDefinition($format)) {
441 $this->format = self::getFormatDefinition($format);
443 $this->format = $format;
446 $this->formatLineCount = substr_count($this->format, "\n");
450 * Sets the progress bar maximal steps.
452 * @param int $max The progress bar max steps
454 private function setMaxSteps($max)
456 $this->max = max(0, (int) $max);
457 $this->stepWidth = $this->max ? Helper::strlen($this->max) : 4;
461 * Overwrites a previous message to the output.
463 * @param string $message The message
465 private function overwrite($message)
467 if ($this->overwrite) {
468 if (!$this->firstRun) {
469 // Move the cursor to the beginning of the line
470 $this->output->write("\x0D");
473 $this->output->write("\x1B[2K");
475 // Erase previous lines
476 if ($this->formatLineCount > 0) {
477 $this->output->write(str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount));
480 } elseif ($this->step > 0) {
481 $this->output->writeln('');
484 $this->firstRun = false;
486 $this->output->write($message);
489 private function determineBestFormat()
491 switch ($this->output->getVerbosity()) {
492 // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
493 case OutputInterface::VERBOSITY_VERBOSE:
494 return $this->max ? 'verbose' : 'verbose_nomax';
495 case OutputInterface::VERBOSITY_VERY_VERBOSE:
496 return $this->max ? 'very_verbose' : 'very_verbose_nomax';
497 case OutputInterface::VERBOSITY_DEBUG:
498 return $this->max ? 'debug' : 'debug_nomax';
500 return $this->max ? 'normal' : 'normal_nomax';
504 private static function initPlaceholderFormatters()
507 'bar' => function (ProgressBar $bar, OutputInterface $output) {
508 $completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getProgress() % $bar->getBarWidth());
509 $display = str_repeat($bar->getBarCharacter(), $completeBars);
510 if ($completeBars < $bar->getBarWidth()) {
511 $emptyBars = $bar->getBarWidth() - $completeBars - Helper::strlenWithoutDecoration($output->getFormatter(), $bar->getProgressCharacter());
512 $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
517 'elapsed' => function (ProgressBar $bar) {
518 return Helper::formatTime(time() - $bar->getStartTime());
520 'remaining' => function (ProgressBar $bar) {
521 if (!$bar->getMaxSteps()) {
522 throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
525 if (!$bar->getProgress()) {
528 $remaining = round((time() - $bar->getStartTime()) / $bar->getProgress() * ($bar->getMaxSteps() - $bar->getProgress()));
531 return Helper::formatTime($remaining);
533 'estimated' => function (ProgressBar $bar) {
534 if (!$bar->getMaxSteps()) {
535 throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
538 if (!$bar->getProgress()) {
541 $estimated = round((time() - $bar->getStartTime()) / $bar->getProgress() * $bar->getMaxSteps());
544 return Helper::formatTime($estimated);
546 'memory' => function (ProgressBar $bar) {
547 return Helper::formatMemory(memory_get_usage(true));
549 'current' => function (ProgressBar $bar) {
550 return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', STR_PAD_LEFT);
552 'max' => function (ProgressBar $bar) {
553 return $bar->getMaxSteps();
555 'percent' => function (ProgressBar $bar) {
556 return floor($bar->getProgressPercent() * 100);
561 private static function initFormats()
564 'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
565 'normal_nomax' => ' %current% [%bar%]',
567 'verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
568 'verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
570 'very_verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
571 'very_verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
573 'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
574 'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
581 private function buildLine()
583 $regex = "{%([a-z\-_]+)(?:\:([^%]+))?%}i";
584 $callback = function ($matches) {
585 if ($formatter = $this::getPlaceholderFormatterDefinition($matches[1])) {
586 $text = \call_user_func($formatter, $this, $this->output);
587 } elseif (isset($this->messages[$matches[1]])) {
588 $text = $this->messages[$matches[1]];
593 if (isset($matches[2])) {
594 $text = sprintf('%'.$matches[2], $text);
599 $line = preg_replace_callback($regex, $callback, $this->format);
601 // gets string length for each sub line with multiline format
602 $linesLength = array_map(function ($subLine) {
603 return Helper::strlenWithoutDecoration($this->output->getFormatter(), rtrim($subLine, "\r"));
604 }, explode("\n", $line));
606 $linesWidth = max($linesLength);
608 $terminalWidth = $this->terminal->getWidth();
609 if ($linesWidth <= $terminalWidth) {
613 $this->setBarWidth($this->barWidth - $linesWidth + $terminalWidth);
615 return preg_replace_callback($regex, $callback, $this->format);