-
Notifications
You must be signed in to change notification settings - Fork 0
/
FixedTimeWindowBasedRecordStrategy.php
87 lines (73 loc) · 1.97 KB
/
FixedTimeWindowBasedRecordStrategy.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
<?php
declare(strict_types = 1);
namespace Interrupt\RecordStrategies;
use DateInterval;
use Interrupt\Contracts\RecordStrategyInterface;
use Psr\Clock\ClockInterface;
/**
* @link https://gist.github.com/tengergou/b823b217180005224362ec1a82dac79a
*/
final class FixedTimeWindowBasedRecordStrategy implements RecordStrategyInterface {
private ClockInterface $clock;
/**
* Window size interval.
* Default: 15 seconds
*/
private DateInterval $windowSize;
/**
* @var array<string, array{\DateTimeImmutable, int}>
*/
private array $records = [];
public function __construct(ClockInterface $clock, DateInterval $windowSize = new DateInterval('PT15S')) {
$this->clock = $clock;
$this->windowSize = $windowSize;
}
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(), 1];
return 1;
}
$now = $this->clock->now();
[$timestamp, $recordCount] = $this->records[$key];
if ($now < $timestamp->add($this->windowSize)) {
$this->records[$key] = [$timestamp, ++$recordCount];
return $recordCount;
}
$this->records[$key] = [$now, 1];
return 1;
}
public function clear(string $key): void {
unset($this->records[$key]);
}
/**
* @return array{
* 0: \Psr\Clock\ClockInterface,
* 1: \DateInterval,
* 2: array<string, array<\DateTimeImmutable, int>>
* }
*/
public function __serialize(): array {
return [
$this->clock,
$this->windowSize,
$this->records
];
}
/**
* @param array{
* 0: \Psr\Clock\ClockInterface,
* 1: \DateInterval,
* 2: array<string, array<\DateTimeImmutable, int>>
* } $data
*/
public function __unserialize(array $data): void {
[
$this->clock,
$this->windowSize,
$this->records
] = $data;
}
}