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\Output\ConsoleOutputInterface;
15 use Symfony\Component\Console\Output\OutputInterface;
16 use Symfony\Component\Console\Exception\LogicException;
19 * The ProgressBar provides helpers to display progress output.
21 * @author Fabien Potencier <fabien@symfony.com>
22 * @author Chris Jones <leeked@gmail.com>
27 private $barWidth = 28;
29 private $emptyBarChar = '-';
30 private $progressChar = '>';
32 private $internalFormat;
33 private $redrawFreq = 1;
36 * @var OutputInterface
43 private $percent = 0.0;
44 private $formatLineCount;
45 private $messages = array();
46 private $overwrite = true;
47 private $firstRun = true;
49 private static $formatters;
50 private static $formats;
55 * @param OutputInterface $output An OutputInterface instance
56 * @param int $max Maximum steps (0 if unknown)
58 public function __construct(OutputInterface $output, $max = 0)
60 if ($output instanceof ConsoleOutputInterface) {
61 $output = $output->getErrorOutput();
64 $this->output = $output;
65 $this->setMaxSteps($max);
67 if (!$this->output->isDecorated()) {
68 // disable overwrite when output does not support ANSI codes.
69 $this->overwrite = false;
71 // set a reasonable redraw frequency so output isn't flooded
72 $this->setRedrawFrequency($max / 10);
75 $this->startTime = time();
79 * Sets a placeholder formatter for a given name.
81 * This method also allow you to override an existing placeholder.
83 * @param string $name The placeholder name (including the delimiter char like %)
84 * @param callable $callable A PHP callable
86 public static function setPlaceholderFormatterDefinition($name, $callable)
88 if (!self::$formatters) {
89 self::$formatters = self::initPlaceholderFormatters();
92 self::$formatters[$name] = $callable;
96 * Gets the placeholder formatter for a given name.
98 * @param string $name The placeholder name (including the delimiter char like %)
100 * @return callable|null A PHP callable
102 public static function getPlaceholderFormatterDefinition($name)
104 if (!self::$formatters) {
105 self::$formatters = self::initPlaceholderFormatters();
108 return isset(self::$formatters[$name]) ? self::$formatters[$name] : null;
112 * Sets a format for a given name.
114 * This method also allow you to override an existing format.
116 * @param string $name The format name
117 * @param string $format A format string
119 public static function setFormatDefinition($name, $format)
121 if (!self::$formats) {
122 self::$formats = self::initFormats();
125 self::$formats[$name] = $format;
129 * Gets the format for a given name.
131 * @param string $name The format name
133 * @return string|null A format string
135 public static function getFormatDefinition($name)
137 if (!self::$formats) {
138 self::$formats = self::initFormats();
141 return isset(self::$formats[$name]) ? self::$formats[$name] : null;
145 * Associates a text with a named placeholder.
147 * The text is displayed when the progress bar is rendered but only
148 * when the corresponding placeholder is part of the custom format line
149 * (by wrapping the name with %).
151 * @param string $message The text to associate with the placeholder
152 * @param string $name The name of the placeholder
154 public function setMessage($message, $name = 'message')
156 $this->messages[$name] = $message;
159 public function getMessage($name = 'message')
161 return $this->messages[$name];
165 * Gets the progress bar start time.
167 * @return int The progress bar start time
169 public function getStartTime()
171 return $this->startTime;
175 * Gets the progress bar maximal steps.
177 * @return int The progress bar max steps
179 public function getMaxSteps()
185 * Gets the progress bar step.
187 * @deprecated since version 2.6, to be removed in 3.0. Use {@link getProgress()} instead.
189 * @return int The progress bar step
191 public function getStep()
193 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the getProgress() method instead.', E_USER_DEPRECATED);
195 return $this->getProgress();
199 * Gets the current step position.
201 * @return int The progress bar step
203 public function getProgress()
209 * Gets the progress bar step width.
211 * @internal This method is public for PHP 5.3 compatibility, it should not be used.
213 * @return int The progress bar step width
215 public function getStepWidth()
217 return $this->stepWidth;
221 * Gets the current progress bar percent.
223 * @return float The current progress bar percent
225 public function getProgressPercent()
227 return $this->percent;
231 * Sets the progress bar width.
233 * @param int $size The progress bar size
235 public function setBarWidth($size)
237 $this->barWidth = (int) $size;
241 * Gets the progress bar width.
243 * @return int The progress bar size
245 public function getBarWidth()
247 return $this->barWidth;
251 * Sets the bar character.
253 * @param string $char A character
255 public function setBarCharacter($char)
257 $this->barChar = $char;
261 * Gets the bar character.
263 * @return string A character
265 public function getBarCharacter()
267 if (null === $this->barChar) {
268 return $this->max ? '=' : $this->emptyBarChar;
271 return $this->barChar;
275 * Sets the empty bar character.
277 * @param string $char A character
279 public function setEmptyBarCharacter($char)
281 $this->emptyBarChar = $char;
285 * Gets the empty bar character.
287 * @return string A character
289 public function getEmptyBarCharacter()
291 return $this->emptyBarChar;
295 * Sets the progress bar character.
297 * @param string $char A character
299 public function setProgressCharacter($char)
301 $this->progressChar = $char;
305 * Gets the progress bar character.
307 * @return string A character
309 public function getProgressCharacter()
311 return $this->progressChar;
315 * Sets the progress bar format.
317 * @param string $format The format
319 public function setFormat($format)
321 $this->format = null;
322 $this->internalFormat = $format;
326 * Sets the redraw frequency.
328 * @param int|float $freq The frequency in steps
330 public function setRedrawFrequency($freq)
332 $this->redrawFreq = max((int) $freq, 1);
336 * Starts the progress output.
338 * @param int|null $max Number of steps to complete the bar (0 if indeterminate), null to leave unchanged
340 public function start($max = null)
342 $this->startTime = time();
344 $this->percent = 0.0;
347 $this->setMaxSteps($max);
354 * Advances the progress output X steps.
356 * @param int $step Number of steps to advance
358 * @throws LogicException
360 public function advance($step = 1)
362 $this->setProgress($this->step + $step);
366 * Sets the current progress.
368 * @deprecated since version 2.6, to be removed in 3.0. Use {@link setProgress()} instead.
370 * @param int $step The current progress
372 * @throws LogicException
374 public function setCurrent($step)
376 @trigger_error('The '.__METHOD__.' method is deprecated since version 2.6 and will be removed in 3.0. Use the setProgress() method instead.', E_USER_DEPRECATED);
378 $this->setProgress($step);
382 * Sets whether to overwrite the progressbar, false for new line.
384 * @param bool $overwrite
386 public function setOverwrite($overwrite)
388 $this->overwrite = (bool) $overwrite;
392 * Sets the current progress.
394 * @param int $step The current progress
396 * @throws LogicException
398 public function setProgress($step)
401 if ($step < $this->step) {
402 throw new LogicException('You can\'t regress the progress bar.');
405 if ($this->max && $step > $this->max) {
409 $prevPeriod = (int) ($this->step / $this->redrawFreq);
410 $currPeriod = (int) ($step / $this->redrawFreq);
412 $this->percent = $this->max ? (float) $this->step / $this->max : 0;
413 if ($prevPeriod !== $currPeriod || $this->max === $step) {
419 * Finishes the progress output.
421 public function finish()
424 $this->max = $this->step;
427 if ($this->step === $this->max && !$this->overwrite) {
428 // prevent double 100% output
432 $this->setProgress($this->max);
436 * Outputs the current progress string.
438 public function display()
440 if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
444 if (null === $this->format) {
445 $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
448 // these 3 variables can be removed in favor of using $this in the closure when support for PHP 5.3 will be dropped.
450 $output = $this->output;
451 $messages = $this->messages;
452 $this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) use ($self, $output, $messages) {
453 if ($formatter = $self::getPlaceholderFormatterDefinition($matches[1])) {
454 $text = call_user_func($formatter, $self, $output);
455 } elseif (isset($messages[$matches[1]])) {
456 $text = $messages[$matches[1]];
461 if (isset($matches[2])) {
462 $text = sprintf('%'.$matches[2], $text);
470 * Removes the progress bar from the current line.
472 * This is useful if you wish to write some output
473 * while a progress bar is running.
474 * Call display() to show the progress bar again.
476 public function clear()
478 if (!$this->overwrite) {
482 if (null === $this->format) {
483 $this->setRealFormat($this->internalFormat ?: $this->determineBestFormat());
486 $this->overwrite('');
490 * Sets the progress bar format.
492 * @param string $format The format
494 private function setRealFormat($format)
496 // try to use the _nomax variant if available
497 if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) {
498 $this->format = self::getFormatDefinition($format.'_nomax');
499 } elseif (null !== self::getFormatDefinition($format)) {
500 $this->format = self::getFormatDefinition($format);
502 $this->format = $format;
505 $this->formatLineCount = substr_count($this->format, "\n");
509 * Sets the progress bar maximal steps.
511 * @param int $max The progress bar max steps
513 private function setMaxSteps($max)
515 $this->max = max(0, (int) $max);
516 $this->stepWidth = $this->max ? Helper::strlen($this->max) : 4;
520 * Overwrites a previous message to the output.
522 * @param string $message The message
524 private function overwrite($message)
526 if ($this->overwrite) {
527 if (!$this->firstRun) {
528 // Move the cursor to the beginning of the line
529 $this->output->write("\x0D");
532 $this->output->write("\x1B[2K");
534 // Erase previous lines
535 if ($this->formatLineCount > 0) {
536 $this->output->write(str_repeat("\x1B[1A\x1B[2K", $this->formatLineCount));
539 } elseif ($this->step > 0) {
540 $this->output->writeln('');
543 $this->firstRun = false;
545 $this->output->write($message);
548 private function determineBestFormat()
550 switch ($this->output->getVerbosity()) {
551 // OutputInterface::VERBOSITY_QUIET: display is disabled anyway
552 case OutputInterface::VERBOSITY_VERBOSE:
553 return $this->max ? 'verbose' : 'verbose_nomax';
554 case OutputInterface::VERBOSITY_VERY_VERBOSE:
555 return $this->max ? 'very_verbose' : 'very_verbose_nomax';
556 case OutputInterface::VERBOSITY_DEBUG:
557 return $this->max ? 'debug' : 'debug_nomax';
559 return $this->max ? 'normal' : 'normal_nomax';
563 private static function initPlaceholderFormatters()
566 'bar' => function (ProgressBar $bar, OutputInterface $output) {
567 $completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getProgress() % $bar->getBarWidth());
568 $display = str_repeat($bar->getBarCharacter(), $completeBars);
569 if ($completeBars < $bar->getBarWidth()) {
570 $emptyBars = $bar->getBarWidth() - $completeBars - Helper::strlenWithoutDecoration($output->getFormatter(), $bar->getProgressCharacter());
571 $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
576 'elapsed' => function (ProgressBar $bar) {
577 return Helper::formatTime(time() - $bar->getStartTime());
579 'remaining' => function (ProgressBar $bar) {
580 if (!$bar->getMaxSteps()) {
581 throw new LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
584 if (!$bar->getProgress()) {
587 $remaining = round((time() - $bar->getStartTime()) / $bar->getProgress() * ($bar->getMaxSteps() - $bar->getProgress()));
590 return Helper::formatTime($remaining);
592 'estimated' => function (ProgressBar $bar) {
593 if (!$bar->getMaxSteps()) {
594 throw new LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
597 if (!$bar->getProgress()) {
600 $estimated = round((time() - $bar->getStartTime()) / $bar->getProgress() * $bar->getMaxSteps());
603 return Helper::formatTime($estimated);
605 'memory' => function (ProgressBar $bar) {
606 return Helper::formatMemory(memory_get_usage(true));
608 'current' => function (ProgressBar $bar) {
609 return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', STR_PAD_LEFT);
611 'max' => function (ProgressBar $bar) {
612 return $bar->getMaxSteps();
614 'percent' => function (ProgressBar $bar) {
615 return floor($bar->getProgressPercent() * 100);
620 private static function initFormats()
623 'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
624 'normal_nomax' => ' %current% [%bar%]',
626 'verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
627 'verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
629 'very_verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
630 'very_verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
632 'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
633 'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',