Newer
Older
smart-home-server / server / SHServ / Tools / RateLimiter.php
<?php

namespace SHServ\Tools;

class RateLimiter {
	protected static array $requests = [];
	protected int $maxRequests;
	protected int $windowSeconds;

	public function __construct(int $maxRequests = 60, int $windowSeconds = 60) {
		$this -> maxRequests = $maxRequests;
		$this -> windowSeconds = $windowSeconds;
	}

	public function check(String $key): bool {
		$now = time();
		if(!isset(self::$requests[$key])) {
			self::$requests[$key] = [];
		}

		// Удаляем устаревшие записи
		self::$requests[$key] = array_filter(self::$requests[$key], function($timestamp) use ($now) {
			return $now - $timestamp < $this -> windowSeconds;
		});

		if(count(self::$requests[$key]) >= $this -> maxRequests) {
			return false;
		}

		self::$requests[$key][] = $now;
		return true;
	}
}