-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstate.php
More file actions
100 lines (82 loc) · 2.05 KB
/
Copy pathstate.php
File metadata and controls
100 lines (82 loc) · 2.05 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
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
<?php
class Update {
private $value;
private $diff;
public function __construct($value, $diff) {
$this->value = $value;
$this->diff = $diff;
}
public function getValue() {
return $this->value;
}
public function getDiff() {
return $this->diff;
}
}
class State {
private $state;
private $timestamp;
private $valid;
private $history;
public function __construct($collectHistory = false) {
$this->state = array();
$this->timestamp = 0;
$this->valid = true;
// Define $history as a local variable
$this->history = null;
if ($collectHistory) {
$this->history = array();
}
}
public function get_history() {
return $this->history;
}
public function get_state() {
$list = array();
foreach ($this->state as $key => $value) {
$clone = json_decode($key);
$i = 0;
while ($i < $value) {
$list[] = $clone;
$i++;
}
}
return $list;
}
public function validate($timestamp) {
if (!$this->valid) {
throw new Exception("Invalid state.");
} elseif ($timestamp < $this->timestamp) {
echo "Invalid timestamp.";
$this->valid = false;
throw new Exception("Update with timestamp ($timestamp) is lower than the last timestamp ({$this->timestamp}). Invalid state.");
}
}
public function process(Update $update) {
$value = json_encode($update->getValue());
$diff = $update->getDiff();
if (isset($this->state[$value])) {
$count = $this->state[$value] + $diff;
} else {
$count = $diff;
}
if ($count <= 0) {
unset($this->state[$value]);
} else {
$this->state[$value] = $count;
}
// Add the update to the history array
if ($this->history !== null) {
$this->history[] = $update;
}
}
public function update($updates, $timestamp) {
if (count($updates) > 0) {
$this->validate($timestamp);
$this->timestamp = $timestamp;
foreach ($updates as $update) {
$this->process($update);
}
}
}
}