-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathTimeLimit.php
More file actions
121 lines (103 loc) · 2.27 KB
/
TimeLimit.php
File metadata and controls
121 lines (103 loc) · 2.27 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<?php
namespace Utopia\Abuse\Adapters;
use Throwable;
use Utopia\Abuse\Adapter;
abstract class TimeLimit extends Adapter
{
/**
* @var int
*/
protected int $limit = 0;
/**
* @var int|null
*/
protected ?int $count = null;
/**
* @var int
*/
protected int $timestamp;
/**
* Check
*
* Checks if number of counts is bigger or smaller than current limit
*
* @param string $key
* @param int $timestamp
* @return int
*
* @throws \Exception
*/
abstract protected function count(string $key, int $timestamp): int;
abstract protected function hit(string $key, int $timestamp): void;
abstract protected function set(string $key, int $timestamp, int $value): void;
/**
* Check
*
* Checks if number of counts is bigger or smaller than current limit. limit 0 is equal to unlimited
*
* @return bool
*
* @throws \Exception|Throwable
*/
public function check(): bool
{
if (0 == $this->limit) {
return false;
}
$key = $this->parseKey();
if ($this->limit > $this->count($key, $this->timestamp)) {
$this->hit($key, $this->timestamp);
return false;
}
return true;
}
/**
* Remaining
*
* Returns the number of current remaining counts
*
* @return int
*
* @throws \Exception
*/
public function remaining(): int
{
$left = $this->limit - ($this->count($this->parseKey(), $this->timestamp) + 1); // Add one because we need to say how many left not how many done
return (0 > $left) ? 0 : $left;
}
/**
* Limit
*
* Return the limit integer
*
* @return int
*/
public function limit(): int
{
return $this->limit;
}
/**
* Time
*
* Return the timestamp
*
* @return int
*/
public function time(): int
{
return $this->timestamp;
}
/**
* Reset
*
* Reset the count to 0 for the current key and timestamp
*
* @return void
*
* @throws \Exception
*/
public function reset(): void
{
$this->set($this->parseKey(), $this->timestamp, 0);
}
}