1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace EngineWorks\ProgressStatus; |
6
|
|
|
|
7
|
|
|
use SplObserver; |
8
|
|
|
use SplSubject; |
9
|
|
|
|
10
|
|
|
class Progress implements SplSubject, ProgressInterface |
11
|
|
|
{ |
12
|
|
|
use SplSubjectWithObserversTrait; |
13
|
|
|
|
14
|
|
|
/** @var Status */ |
15
|
|
|
private $status; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Progress constructor. |
19
|
|
|
* |
20
|
|
|
* @param Status|null $initialStatus when null it creates an empty State using make method |
21
|
|
|
* @param iterable<SplObserver> $observers |
22
|
|
|
*/ |
23
|
22 |
|
public function __construct(Status $initialStatus = null, iterable $observers = []) |
24
|
|
|
{ |
25
|
22 |
|
$this->constructSplSubjectWithObservers(); |
26
|
22 |
|
$this->status = $initialStatus ?: Status::make(); |
27
|
22 |
|
foreach ($observers as $observer) { |
28
|
1 |
|
$this->attach($observer); |
29
|
|
|
} |
30
|
22 |
|
$this->notify(); |
31
|
|
|
} |
32
|
|
|
|
33
|
8 |
|
public function getStatus(): Status |
34
|
|
|
{ |
35
|
8 |
|
return $this->status; |
36
|
|
|
} |
37
|
|
|
|
38
|
2 |
|
public function increase(string $message = '', int $increase = 1): void |
39
|
|
|
{ |
40
|
2 |
|
$this->update($message, $this->status->getValue() + $increase); |
41
|
|
|
} |
42
|
|
|
|
43
|
4 |
|
public function update( |
44
|
|
|
string $message = '', |
45
|
|
|
int $value = null, |
46
|
|
|
int $total = null, |
47
|
|
|
int $startTime = null, |
48
|
|
|
int $current = null |
49
|
|
|
): void { |
50
|
4 |
|
$newStatus = new Status( |
51
|
4 |
|
$current ?? time(), |
52
|
4 |
|
$startTime ?? $this->status->getStart(), |
53
|
4 |
|
$value ?? $this->status->getValue(), |
54
|
4 |
|
$total ?? $this->status->getTotal(), |
55
|
4 |
|
$message ?: $this->status->getMessage(), |
56
|
4 |
|
); |
57
|
4 |
|
$shouldNotifyChange = $this->shouldNotifyChange($this->status, $newStatus); |
58
|
4 |
|
$this->status = $newStatus; |
59
|
4 |
|
if ($shouldNotifyChange) { |
60
|
3 |
|
$this->notify(); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
10 |
|
public function shouldNotifyChange(Status $current, Status $newStatus): bool |
65
|
|
|
{ |
66
|
10 |
|
return ($current->getValue() !== $newStatus->getValue()) |
67
|
10 |
|
|| ($current->getMessage() !== $newStatus->getMessage()) |
68
|
10 |
|
|| ($current->getTotal() !== $newStatus->getTotal()) |
69
|
10 |
|
|| ($current->getStart() !== $newStatus->getStart()); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|