forked from NativePHP/laravel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgressBar.php
86 lines (65 loc) · 1.99 KB
/
ProgressBar.php
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace Native\Laravel;
use Native\Laravel\Client\Client;
class ProgressBar
{
protected float $percent = 0;
protected int $step = 0;
protected float $lastWriteTime = 0;
protected float $minSecondsBetweenRedraws = 0.1;
protected float $maxSecondsBetweenRedraws = 1;
public function __construct(protected int $maxSteps, protected Client $client) {}
public static function create(int $maxSteps): static
{
return new static($maxSteps, new Client);
}
public function start()
{
$this->lastWriteTime = microtime(true);
$this->setProgress(0);
}
public function advance($step = 1)
{
$this->setProgress($this->step + $step);
}
public function setProgress(int $step)
{
if ($this->maxSteps && $step > $this->maxSteps) {
$this->maxSteps = $step;
} elseif ($step < 0) {
$step = 0;
}
$redrawFreq = 1;
$prevPeriod = (int) ($this->step / $redrawFreq);
$currPeriod = (int) ($step / $redrawFreq);
$this->step = $step;
$this->percent = $this->maxSteps ? (float) $this->step / $this->maxSteps : 0;
$timeInterval = microtime(true) - $this->lastWriteTime;
// Draw regardless of other limits
if ($this->maxSteps === $step) {
$this->display();
return;
}
// Throttling
if ($timeInterval < $this->minSecondsBetweenRedraws) {
return;
}
// Draw each step period, but not too late
if ($prevPeriod !== $currPeriod || $timeInterval >= $this->maxSecondsBetweenRedraws) {
$this->display();
}
}
public function finish()
{
$this->client->post('progress-bar/update', [
'percent' => -1,
]);
}
public function display()
{
$this->lastWriteTime = microtime(true);
$this->client->post('progress-bar/update', [
'percent' => $this->percent,
]);
}
}