<?php
namespace App\EventSubscriber;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\RateLimiter\RateLimiterFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
class AuthenticatedRateLimiterSubscriber implements EventSubscriberInterface
{
/**
* @var RateLimiterFactory
*/
private $authenticatedApiLimiter;
public function __construct(RateLimiterFactory $authenticatedApiLimiter)
{
$this->authenticatedApiLimiter = $authenticatedApiLimiter;
}
public static function getSubscribedEvents(): array
{
return [
RequestEvent::class => 'onKernelRequest',
];
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
if ($request->isMethod('post')) {
$apiKey = $request->headers->get('apikey');
$authLimiter = $this->authenticatedApiLimiter->create($apiKey);
$authLimiter->reserve(1)->wait();
if (false === $authLimiter->consume(1)->isAccepted()) {
throw new TooManyRequestsHttpException();
}
}
/* $apiKey = $request->headers->get('apikey');
$limiter = $this->authenticatedApiLimiter->create($apiKey);
// this blocks the application until the given number of tokens can be consumed
$limiter->reserve(1)->wait();
if (false === $limiter->consume(1)->isAccepted()) {
throw new TooManyRequestsHttpException();
} */
}
}