src/EventSubscriber/RateLimiterSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\HttpKernel\Event\RequestEvent;
  4. use Symfony\Component\RateLimiter\RateLimiterFactory;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
  7. class RateLimiterSubscriber implements EventSubscriberInterface
  8. {
  9.     /**
  10.      * @var RateLimiterFactory
  11.      */
  12.     private $anonymousApiLimiter;
  13.     public function __construct(RateLimiterFactory $anonymousApiLimiter)
  14.     {
  15.         $this->anonymousApiLimiter $anonymousApiLimiter;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             RequestEvent::class => 'onKernelRequest',
  21.         ];
  22.     }
  23.     public function onKernelRequest(RequestEvent $event): void
  24.     {
  25.         $request $event->getRequest();
  26.         if ($request->isMethod('get')) {
  27.             $limiter $this->anonymousApiLimiter->create($request->getClientIp());
  28.             /* $limit = $limiter->consume();
  29.             $headers = [
  30.                 'X-RateLimit-Remaining' => $limit->getRemainingTokens(),
  31.                 'X-RateLimit-Retry-After' => $limit->getRetryAfter()->getTimestamp(),
  32.                 'X-RateLimit-Limit' => $limit->getLimit(),
  33.             ]; */
  34.             if (false === $limiter->consume(1)->isAccepted()) {
  35.                 throw new TooManyRequestsHttpException();
  36.             }
  37.         }
  38.     }
  39. }