-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathState.php
135 lines (105 loc) · 2.67 KB
/
State.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
<?php
namespace FSMgasm;
use Exception;
abstract class State
{
protected int $duration = 0;
private bool $started = false;
private bool $ended = false;
private bool $frozen = false;
private int $startTime;
private bool $updating = false;
protected function getDuration(): int
{
return $this->duration;
}
public function hasStarted(): bool
{
return $this->started;
}
public function hasEnded(): bool
{
return $this->ended;
}
public function isFrozen(): bool
{
return $this->frozen;
}
public function setFrozen(bool $frozen): void
{
$this->frozen = $frozen;
}
public function freeze(): void
{
$this->setFrozen(true);
}
public function unfreeze(): void
{
$this->setFrozen(false);
}
public function start(): void
{
if ($this->started || $this->ended) {
return;
}
$this->started = true;
$this->startTime = time();
try {
$this->onStart();
} catch (Exception) {
$className = get_class($this);
print_r("Exception during $className start\n");
}
}
protected abstract function onStart(): void;
public function update(): void
{
if (!$this->started || $this->ended || $this->updating) {
return;
}
$this->updating = true;
if ($this->isReadyToEnd() && !$this->frozen) {
$this->end();
return;
}
try {
$this->onUpdate();
} catch (Exception) {
$className = get_class($this);
print_r("Exception during $className update\n");
}
$this->updating = false;
}
protected abstract function onUpdate(): void;
public function end(): void
{
if (!$this->started || $this->ended) {
return;
}
$this->ended = true;
try {
$this->onEnd();
} catch (Exception) {
$className = get_class($this);
print_r("Exception during $className end\n");
}
}
protected abstract function onEnd(): void;
public function isReadyToEnd(): bool
{
return $this->ended || $this->getRemainingDuration() == 0;
}
public function getRemainingDuration(): int
{
$sinceStart = (time() - $this->startTime);
$remaining = $this->getDuration() - $sinceStart;
return max($remaining, 0);
}
public function cleanup(): void
{
$this->started = false;
$this->ended = false;
$this->frozen = false;
$this->updating = false;
}
}