Add an iterate method to the ProgressBar class

This commit is contained in:
Jérôme Vasseur 2019-01-03 00:00:39 +01:00
parent 5aa0967f9f
commit eb355314b0
5 changed files with 58 additions and 2 deletions

View File

@ -32,7 +32,8 @@
"symfony/polyfill-ctype": "~1.8",
"symfony/polyfill-intl-icu": "~1.0",
"symfony/polyfill-mbstring": "~1.0",
"symfony/polyfill-php72": "~1.5"
"symfony/polyfill-php72": "~1.5",
"symfony/polyfill-php73": "^1.8"
},
"replace": {
"symfony/asset": "self.version",

View File

@ -5,6 +5,7 @@ CHANGELOG
-----
* added support for hyperlinks
* added `ProgressBar::iterate()` method that simplify updating the progress bar when iterating
4.2.0
-----

View File

@ -243,6 +243,24 @@ final class ProgressBar
$this->redrawFreq = max($freq, 1);
}
/**
* Returns an iterator that will automatically update the progress bar when iterated.
*
* @param int|null $max Number of steps to complete the bar (0 if indeterminate), if null it will be inferred from $iterable
*/
public function iterate(iterable $iterable, ?int $max = null): iterable
{
$this->start($max ?? (\is_countable($iterable) ? \count($iterable) : 0));
foreach ($iterable as $key => $value) {
yield $key => $value;
$this->advance();
}
$this->finish();
}
/**
* Starts the progress output.
*

View File

@ -867,6 +867,41 @@ class ProgressBarTest extends TestCase
];
}
public function testIterate(): void
{
$bar = new ProgressBar($output = $this->getOutputStream());
$this->assertEquals([1, 2], \iterator_to_array($bar->iterate([1, 2])));
rewind($output->getStream());
$this->assertEquals(
' 0/2 [>---------------------------] 0%'.
$this->generateOutput(' 1/2 [==============>-------------] 50%').
$this->generateOutput(' 2/2 [============================] 100%').
$this->generateOutput(' 2/2 [============================] 100%'),
stream_get_contents($output->getStream())
);
}
public function testIterateUncountable(): void
{
$bar = new ProgressBar($output = $this->getOutputStream());
$this->assertEquals([1, 2], \iterator_to_array($bar->iterate((function () {
yield 1;
yield 2;
})())));
rewind($output->getStream());
$this->assertEquals(
' 0 [>---------------------------]'.
$this->generateOutput(' 1 [->--------------------------]').
$this->generateOutput(' 2 [-->-------------------------]').
$this->generateOutput(' 2 [============================]'),
stream_get_contents($output->getStream())
);
}
protected function getOutputStream($decorated = true, $verbosity = StreamOutput::VERBOSITY_NORMAL)
{
return new StreamOutput(fopen('php://memory', 'r+', false), $verbosity, $decorated);

View File

@ -18,7 +18,8 @@
"require": {
"php": "^7.1.3",
"symfony/contracts": "^1.0",
"symfony/polyfill-mbstring": "~1.0"
"symfony/polyfill-mbstring": "~1.0",
"symfony/polyfill-php73": "^1.8"
},
"require-dev": {
"symfony/config": "~3.4|~4.0",