Skip to content

Commit 3d58ab5

Browse files
maidmaidfabpot
authored andcommitted
[Console] Fix bar width with multilines ProgressBar's format
1 parent f296648 commit 3d58ab5

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/Symfony/Component/Console/Helper/ProgressBar.php

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -603,13 +603,19 @@ private function buildLine()
603603
};
604604
$line = preg_replace_callback($regex, $callback, $this->format);
605605

606-
$lineLength = Helper::strlenWithoutDecoration($this->output->getFormatter(), $line);
606+
// gets string length for each sub line with multiline format
607+
$linesLength = array_map(function ($subLine) {
608+
return Helper::strlenWithoutDecoration($this->output->getFormatter(), rtrim($subLine, "\r"));
609+
}, explode("\n", $line));
610+
611+
$linesWidth = max($linesLength);
612+
607613
$terminalWidth = $this->terminal->getWidth();
608-
if ($lineLength <= $terminalWidth) {
614+
if ($linesWidth <= $terminalWidth) {
609615
return $line;
610616
}
611617

612-
$this->setBarWidth($this->barWidth - $lineLength + $terminalWidth);
618+
$this->setBarWidth($this->barWidth - $linesWidth + $terminalWidth);
613619

614620
return preg_replace_callback($regex, $callback, $this->format);
615621
}

src/Symfony/Component/Console/Tests/Helper/ProgressBarTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -754,4 +754,22 @@ protected function generateOutput($expected)
754754

755755
return "\x0D\x1B[2K".($count ? str_repeat("\x1B[1A\x1B[2K", $count) : '').$expected;
756756
}
757+
758+
public function testBarWidthWithMultilineFormat()
759+
{
760+
putenv('COLUMNS=10');
761+
762+
$bar = new ProgressBar($output = $this->getOutputStream());
763+
$bar->setFormat("%bar%\n0123456789");
764+
765+
// before starting
766+
$bar->setBarWidth(5);
767+
$this->assertEquals(5, $bar->getBarWidth());
768+
769+
// after starting
770+
$bar->start();
771+
rewind($output->getStream());
772+
$this->assertEquals(5, $bar->getBarWidth(), stream_get_contents($output->getStream()));
773+
putenv('COLUMNS=120');
774+
}
757775
}

0 commit comments

Comments
 (0)