Skip to content

Commit 78dd2ab

Browse files
authored
Merge pull request #27 from rayanlevert/2.2.1
v2.2.1
2 parents 74c68c1 + 93de49e commit 78dd2ab

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

src/ProgressBar.php

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

147147
if ($this->title) {
148-
print sprintf(self::UP . self::LEFT . "\33[2K" . $this->title . self::DOWN, 1, 1000, 1);
148+
// Escape percentage signs in the title to prevent sprintf errors
149+
$escapedTitle = str_replace('%', '%%', $this->title);
150+
151+
print sprintf(self::UP . self::LEFT . "\33[2K" . $escapedTitle . self::DOWN, 1, 1000, 1);
149152
}
150153

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

tests/ProgressBar/ProgressBarTest.php

Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,48 @@ public function testStartWithTitleDifferentColor(): void
9494
ob_clean();
9595
}
9696

97-
/**
98-
* @test ->advance() without calling ->start() -> does not do anything
99-
*/
97+
public function testTitleWithSinglePercentageSign(): void
98+
{
99+
// Test with a single percentage sign
100+
(new ProgressBar(5))->setTitle('Progress: 50%', Foreground::GREEN)->start();
101+
102+
$this->assertStringStartsWith(
103+
"\n\n\e[1A\e[1000D\33[2K" . Style::stylize("\tProgress: 50%", fg: Foreground::GREEN)
104+
. "\e[1B\e[1000D\33[2K\t0 / 5 [ ] 0%",
105+
ob_get_contents()
106+
);
107+
108+
ob_clean();
109+
}
110+
111+
public function testTitleWithDoublePercentageSign(): void
112+
{
113+
// Test with a double percentage sign
114+
(new ProgressBar(5))->setTitle('Progress: 100%%')->start();
115+
116+
$this->assertStringStartsWith(
117+
"\n\n\e[1A\e[1000D\33[2K" . Style::stylize("\tProgress: 100%%", fg: Foreground::BLUE)
118+
. "\e[1B\e[1000D\33[2K\t0 / 5 [ ] 0%",
119+
ob_get_contents()
120+
);
121+
122+
ob_clean();
123+
}
124+
125+
public function testTitleWithMultiplePercentageSigns(): void
126+
{
127+
// Test with multiple percentage signs
128+
(new ProgressBar(5))->setTitle('Progress: 25% and 75%')->start();
129+
130+
$this->assertStringStartsWith(
131+
"\n\n\e[1A\e[1000D\33[2K" . Style::stylize("\tProgress: 25% and 75%", fg: Foreground::BLUE)
132+
. "\e[1B\e[1000D\33[2K\t0 / 5 [ ] 0%",
133+
ob_get_contents()
134+
);
135+
136+
ob_clean();
137+
}
138+
100139
public function testAdvanceWithoutStarting(): void
101140
{
102141
$this->expectOutputString('');

0 commit comments

Comments
 (0)