-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathProgressBarView.php
More file actions
57 lines (39 loc) · 1.11 KB
/
ProgressBarView.php
File metadata and controls
57 lines (39 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
declare(strict_types=1);
namespace DragonCode\Benchmark\View;
use function floor;
use function max;
use function str_repeat;
class ProgressBarView extends View
{
protected int $current = 0;
protected int $barWidth = 28;
protected int $total = 100;
public function create(int $total): static
{
$this->total = max(1, $total);
$this->display();
return $this;
}
public function advance(int $step = 1): void
{
$this->current += $step;
$this->display();
}
public function finish(): void
{
$this->current = $this->total;
$this->display();
$this->write(PHP_EOL);
}
protected function display(): void
{
$percent = $this->current / $this->total;
$filled = (int) floor($percent * $this->barWidth);
$empty = $this->barWidth - $filled;
$percText = (int) floor($percent * 100);
$bar = str_repeat('▓', $filled) . str_repeat('░', $empty);
$line = " {$this->current}/{$this->total} [{$bar}] {$percText}%";
$this->write("\r" . $line);
}
}