Skip to content

Commit 7e751fa

Browse files
authored
Merge pull request #26 from rayanlevert/bugfix/i25
ProgressBar : ArgumentCountError if the title contains percentage
2 parents 90a2411 + ad34762 commit 7e751fa

File tree

2 files changed

+49
-1
lines changed

2 files changed

+49
-1
lines changed

src/ProgressBar.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,10 @@ public function advance(int $toAdvance = 1): void
153153
}
154154

155155
if ($this->title) {
156-
print sprintf(self::UP . self::LEFT . "\33[2K" . $this->title . self::DOWN, 1, 1000, 1);
156+
// Escape percentage signs in the title to prevent sprintf errors
157+
$escapedTitle = str_replace('%', '%%', $this->title);
158+
159+
print sprintf(self::UP . self::LEFT . "\33[2K" . $escapedTitle . self::DOWN, 1, 1000, 1);
157160
}
158161

159162
// Resets the line placing the cursor leftmost + the current iteration / max

tests/ProgressBar/ProgressBarTest.php

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,51 @@ public function startWithTitleDifferentColor(): void
8383
ob_clean();
8484
}
8585

86+
#[Test]
87+
public function titleWithSinglePercentageSign(): void
88+
{
89+
// Test with a single percentage sign
90+
new ProgressBar(5)->setTitle('Progress: 50%', Foreground::GREEN)->start();
91+
92+
$this->assertStringStartsWith(
93+
"\n\n\e[1A\e[1000D\33[2K" . Style::stylize("\tProgress: 50%", fg: Foreground::GREEN)
94+
. "\e[1B\e[1000D\33[2K\t0 / 5 [ ] 0%",
95+
ob_get_contents()
96+
);
97+
98+
ob_clean();
99+
}
100+
101+
#[Test]
102+
public function titleWithDoublePercentageSign(): void
103+
{
104+
// Test with a double percentage sign
105+
new ProgressBar(5)->setTitle('Progress: 100%%')->start();
106+
107+
$this->assertStringStartsWith(
108+
"\n\n\e[1A\e[1000D\33[2K" . Style::stylize("\tProgress: 100%%", fg: Foreground::BLUE)
109+
. "\e[1B\e[1000D\33[2K\t0 / 5 [ ] 0%",
110+
ob_get_contents()
111+
);
112+
113+
ob_clean();
114+
}
115+
116+
#[Test]
117+
public function titleWithMultiplePercentageSigns(): void
118+
{
119+
// Test with multiple percentage signs
120+
new ProgressBar(5)->setTitle('Progress: 25% and 75%')->start();
121+
122+
$this->assertStringStartsWith(
123+
"\n\n\e[1A\e[1000D\33[2K" . Style::stylize("\tProgress: 25% and 75%", fg: Foreground::BLUE)
124+
. "\e[1B\e[1000D\33[2K\t0 / 5 [ ] 0%",
125+
ob_get_contents()
126+
);
127+
128+
ob_clean();
129+
}
130+
86131
#[Test]
87132
public function advanceWithoutStarting(): void
88133
{

0 commit comments

Comments
 (0)