39 lines
1.1 KiB
PHP
39 lines
1.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
final class RateLimiter
|
|
{
|
|
public function __construct(private string $dir)
|
|
{
|
|
}
|
|
|
|
public function assertAllowed(string $bucket, int $limit, int $windowSeconds): void
|
|
{
|
|
if ($limit < 1) {
|
|
throw new RuntimeException('Rate limit is invalid');
|
|
}
|
|
if (!is_dir($this->dir)) {
|
|
mkdir($this->dir, 0700, true);
|
|
}
|
|
$file = $this->dir . '/' . preg_replace('/[^A-Za-z0-9._-]/', '_', $bucket) . '.json';
|
|
$now = time();
|
|
$events = [];
|
|
if (is_file($file)) {
|
|
$decoded = json_decode((string)file_get_contents($file), true);
|
|
if (is_array($decoded)) {
|
|
foreach ($decoded as $event) {
|
|
if (is_int($event) && $event > $now - $windowSeconds) {
|
|
$events[] = $event;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if (count($events) >= $limit) {
|
|
throw new RuntimeException('Rate limit exceeded');
|
|
}
|
|
$events[] = $now;
|
|
file_put_contents($file, json_encode($events), LOCK_EX);
|
|
@chmod($file, 0600);
|
|
}
|
|
}
|