-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRatelimiter.php
41 lines (34 loc) · 952 Bytes
/
Ratelimiter.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
<?php
class Ratelimiter
{
protected static $allow;
protected static $lastCheck;
/**
* @param int $rate
* @param int $per
*
* @return void
*/
public static function check($rate = 5, $per = 1)
{
self::$lastCheck = self::$lastCheck ?? microtime(true);
self::$allow = self::$allow ?? $rate;
$consumed = 1;
$current = microtime(true);
$timePassed = $current - self::$lastCheck;
self::$lastCheck = $current;
self::$allow += $timePassed * ($rate / $per);
if (self::$allow > $rate) {
self::$allow = $rate;
}
if (self::$allow < $consumed) {
$duration = ($consumed - self::$allow) * ($per / $rate - 1);
self::$lastCheck += $duration;
usleep($per * 1000000);
self::$allow = $rate;
} else {
self::$allow -= $consumed;
}
return;
}
}