-
Notifications
You must be signed in to change notification settings - Fork 0
/
SlidingTimeWindowBasedRecordStrategy.php
115 lines (98 loc) · 2.5 KB
/
SlidingTimeWindowBasedRecordStrategy.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
<?php
declare(strict_types = 1);
namespace Interrupt\RecordStrategies;
use DateInterval;
use Interrupt\Contracts\RecordStrategyInterface;
use Psr\Clock\ClockInterface;
/**
* @link https://gist.github.com/tengergou/822dbb51ab6d15751135e570d14b0a29
*/
final class SlidingTimeWindowBasedRecordStrategy implements RecordStrategyInterface {
private ClockInterface $clock;
/**
* Window size interval.
* Default: 15 seconds
*/
private DateInterval $windowSize;
/**
* Max number of stored records.
* Default: 50 items
*/
private int $maxRecords;
/**
* @var array<string, \DateTimeImmutable[]>
*/
private array $records = [];
public function __construct(
ClockInterface $clock,
DateInterval $windowSize = new DateInterval('PT15S'),
int $maxRecords = 50
) {
$this->clock = $clock;
$this->windowSize = $windowSize;
$this->maxRecords = $maxRecords;
}
public function getWindowSize(): DateInterval {
return $this->windowSize;
}
public function mark(string $key): int {
if (isset($this->records[$key]) === false || count($this->records[$key]) === 0) {
$this->records[$key][] = $this->clock->now();
return 1;
}
$now = $this->clock->now();
$startTime = $this->records[$key][0];
$check = count($this->records[$key]);
while ($check > 0) {
if ($now >= $startTime->add($this->windowSize)) {
$startTime = array_shift($this->records[$key]);
$check--;
continue;
}
break;
}
if ($now <= $startTime->add($this->windowSize)) {
if (count($this->records[$key]) < $this->maxRecords) {
$this->records[$key][] = $now;
}
return count($this->records[$key]);
}
$this->records[$key][] = $now;
return count($this->records[$key]);
}
public function clear(string $key): void {
unset($this->records[$key]);
}
/**
* @return array{
* 0: \Psr\Clock\ClockInterface,
* 1: \DateInterval,
* 2: int,
* 3: array<string, \DateTimeImmutable[]>
* }
*/
public function __serialize(): array {
return [
$this->clock,
$this->windowSize,
$this->maxRecords,
$this->records
];
}
/**
* @param array{
* 0: \Psr\Clock\ClockInterface,
* 1: \DateInterval,
* 2: int,
* 3: array<string, \DateTimeImmutable[]>
* } $data
*/
public function __unserialize(array $data): void {
[
$this->clock,
$this->windowSize,
$this->maxRecords,
$this->records
] = $data;
}
}