[Console][ProgressBar] Allow to advance past max.

This commit is contained in:
Gilles Doge 2014-07-07 17:02:57 +02:00 committed by Stefano Sala
parent 73ca340827
commit 30116859e6
2 changed files with 40 additions and 9 deletions

View File

@ -52,17 +52,14 @@ class ProgressBar
*
* @param OutputInterface $output An OutputInterface instance
* @param int $max Maximum steps (0 if unknown)
*
* @throws \InvalidArgumentException
*/
public function __construct(OutputInterface $output, $max = 0)
{
if (!is_integer($max) || $max < 0) {
throw new \InvalidArgumentException('Max steps should be a positive integer, 0 or null. Got "%s".', $max);
}
// Disabling output when it does not support ANSI codes as it would result in a broken display anyway.
$this->output = $output->isDecorated() ? $output : new NullOutput();
$this->max = (int) $max;
$this->stepWidth = $this->max > 0 ? Helper::strlen($this->max) : 4;
$this->setMaxSteps($max);
if (!self::$formatters) {
self::$formatters = self::initPlaceholderFormatters();
@ -167,6 +164,25 @@ class ProgressBar
return $this->startTime;
}
/**
* Sets the progress bar maximal steps.
*
* @param int The progress bar max steps
*
* @throws \InvalidArgumentException
*/
public function setMaxSteps($max)
{
$max = (int) $max;
if ($max < 0) {
throw new \InvalidArgumentException('Max steps should be a positive integer, 0 or null. Got "%s".', $max);
}
$this->max = $max;
$this->stepWidth = $this->max > 0 ? Helper::strlen($this->max) : 4;
}
/**
* Gets the progress bar maximal steps.
*
@ -338,8 +354,7 @@ class ProgressBar
public function start($max = 0)
{
if (0 !== $max) {
$this->max = $max;
$this->stepWidth = $this->max > 0 ? Helper::strlen($this->max) : 4;
$this->setMaxSteps($max);
}
if (!$this->max) {
@ -377,7 +392,7 @@ class ProgressBar
}
if ($this->max > 0 && $step > $this->max) {
throw new \LogicException('You can\'t advance the progress bar past the max value.');
$this->max = $step;
}
$prevPeriod = intval($this->step / $this->redrawFreq);

View File

@ -71,6 +71,22 @@ class ProgressBarTest extends \PHPUnit_Framework_TestCase
);
}
public function testAdvanceOverMax()
{
$bar = new ProgressBar($output = $this->getOutputStream(), 10);
$bar->setCurrent(9);
$bar->advance();
$bar->advance();
rewind($output->getStream());
$this->assertEquals(
$this->generateOutput(' 9/10 [=========================>--] 90%').
$this->generateOutput(' 10/10 [============================] 100%').
$this->generateOutput(' 11/11 [============================] 100%'),
stream_get_contents($output->getStream())
);
}
public function testCustomizations()
{
$bar = new ProgressBar($output = $this->getOutputStream(), 10);