Skip to content

Commit a2b9ad6

Browse files
Merge pull request #112
Refactor `ProgressBarView`
2 parents 14afff0 + c885c34 commit a2b9ad6

1 file changed

Lines changed: 47 additions & 7 deletions

File tree

src/View/ProgressBarView.php

Lines changed: 47 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -9,19 +9,21 @@
99
use function floor;
1010
use function max;
1111
use function str_repeat;
12+
use function vsprintf;
1213

1314
class ProgressBarView extends View implements ProgressBar
1415
{
1516
protected int $current = 0;
1617

17-
protected int $barWidth = 28;
18+
protected int $width = 28;
1819

1920
protected int $total = 100;
2021

2122
/**
2223
* Creates a progress bar with the specified total number of steps.
2324
*
2425
* @param int $total The total number of steps.
26+
*
2527
* @return $this
2628
*/
2729
public function create(int $total): static
@@ -62,15 +64,53 @@ public function finish(): void
6264
*/
6365
protected function display(): void
6466
{
65-
$percent = $this->current / $this->total;
66-
$filled = (int) floor($percent * $this->barWidth);
67-
$empty = $this->barWidth - $filled;
68-
$percText = (int) floor($percent * 100);
67+
$percent = $this->percent();
6968

70-
$bar = str_repeat('', $filled) . str_repeat('', $empty);
69+
$filled = $this->filledText($percent);
70+
$empty = $this->emptyText($filled);
7171

72-
$line = " {$this->current}/{$this->total} [{$bar}] {$percText}%";
72+
$line = $this->buildLine($filled, $empty, $percent);
7373

7474
$this->write("\r" . $line);
7575
}
76+
77+
protected function buildLine(int $filled, int $empty, float $percent): string
78+
{
79+
return vsprintf(' %s/%s [%s] %s%%', [
80+
$this->numberFormat($this->current),
81+
$this->numberFormat($this->total),
82+
$this->buildBar($filled, $empty),
83+
$this->percentText($percent),
84+
]);
85+
}
86+
87+
protected function buildBar(int $filled, int $empty): string
88+
{
89+
return str_repeat('', $filled) . str_repeat('', $empty);
90+
}
91+
92+
protected function percent(): float
93+
{
94+
return $this->current / $this->total;
95+
}
96+
97+
protected function filledText(float $percent): int
98+
{
99+
return (int) floor($percent * $this->width);
100+
}
101+
102+
protected function emptyText(int $filled): int
103+
{
104+
return $this->width - $filled;
105+
}
106+
107+
protected function percentText(float $percent): int
108+
{
109+
return (int) floor($percent * 100);
110+
}
111+
112+
protected function numberFormat(int $number): string
113+
{
114+
return number_format($number, thousands_separator: "'");
115+
}
76116
}

0 commit comments

Comments
 (0)