|
9 | 9 | use function floor; |
10 | 10 | use function max; |
11 | 11 | use function str_repeat; |
| 12 | +use function vsprintf; |
12 | 13 |
|
13 | 14 | class ProgressBarView extends View implements ProgressBar |
14 | 15 | { |
15 | 16 | protected int $current = 0; |
16 | 17 |
|
17 | | - protected int $barWidth = 28; |
| 18 | + protected int $width = 28; |
18 | 19 |
|
19 | 20 | protected int $total = 100; |
20 | 21 |
|
21 | 22 | /** |
22 | 23 | * Creates a progress bar with the specified total number of steps. |
23 | 24 | * |
24 | 25 | * @param int $total The total number of steps. |
| 26 | + * |
25 | 27 | * @return $this |
26 | 28 | */ |
27 | 29 | public function create(int $total): static |
@@ -62,15 +64,53 @@ public function finish(): void |
62 | 64 | */ |
63 | 65 | protected function display(): void |
64 | 66 | { |
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(); |
69 | 68 |
|
70 | | - $bar = str_repeat('▓', $filled) . str_repeat('░', $empty); |
| 69 | + $filled = $this->filledText($percent); |
| 70 | + $empty = $this->emptyText($filled); |
71 | 71 |
|
72 | | - $line = " {$this->current}/{$this->total} [{$bar}] {$percText}%"; |
| 72 | + $line = $this->buildLine($filled, $empty, $percent); |
73 | 73 |
|
74 | 74 | $this->write("\r" . $line); |
75 | 75 | } |
| 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 | + } |
76 | 116 | } |
0 commit comments