Files
Plenario/src/Service/ThrottleService.php
T
gnilebeinandClaude Opus 5.5 eb319f8c1e
CI / Deploy / test (push) Successful in 49s
CI / Deploy / deploy (push) Failing after 5s
Add initial Plenario live polling app
CakePHP 5.4 app for live polls: create via email without login, manage
via secret admin link, join via code. Includes slide types (choice,
wordcloud, open, scale, content), presenter mode, CSV export, captcha,
throttling, tests and Gitea CI/deploy workflow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 13:24:29 +01:00

46 lines
1.3 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Service;
use Cake\Cache\Cache;
/**
* Very small fixed-window rate limiter backed by the "throttle" cache config.
* Used to limit poll creation and recovery mails per client IP.
*/
class ThrottleService
{
public const WINDOW_SECONDS = 3600;
/**
* Registers a hit and returns whether the action is still allowed.
*
* @param string $bucket Logical action, e.g. "create"
* @param string $identifier Client identifier, e.g. IP address
* @param int $limit Allowed hits per window; <= 0 disables throttling
* @return bool
*/
public function attempt(string $bucket, string $identifier, int $limit): bool
{
if ($limit <= 0) {
return true;
}
$key = 'throttle_' . $bucket . '_' . hash('sha256', $identifier);
$now = time();
/** @var array{start: int, hits: int}|null $state */
$state = Cache::read($key, 'throttle');
if (!is_array($state) || $state['start'] + self::WINDOW_SECONDS <= $now) {
$state = ['start' => $now, 'hits' => 0];
}
if ($state['hits'] >= $limit) {
return false;
}
$state['hits']++;
Cache::write($key, $state, 'throttle');
return true;
}
}