src/EventSubscriber/RateLimiterSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
  6. use Symfony\Component\RateLimiter\RateLimiterFactory;
  7. class RateLimiterSubscriber implements EventSubscriberInterface
  8. {
  9.     public function __construct(
  10.         private RateLimiterFactory $anonymousApiLimiter,
  11.     ) {}
  12.     public static function getSubscribedEvents(): array
  13.     {
  14.         return [
  15.             RequestEvent::class => 'onKernelRequest',
  16.         ];
  17.     }
  18.     public function onKernelRequest(RequestEvent $event): void
  19.     {
  20.         $request $event->getRequest();
  21.         if ($request->isMethod('GET') || $request->isMethod('POST')) {
  22.             $limiter $this->anonymousApiLimiter->create($request->getClientIp());
  23.             if (false === $limiter->consume(1)->isAccepted()) {
  24.                 throw new TooManyRequestsHttpException();
  25.             }
  26.         }
  27.     }
  28. }