src/EventSubscriber/AuthenticatedRateLimiterSubscriber.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 AuthenticatedRateLimiterSubscriber implements EventSubscriberInterface
  8. {
  9.     /**
  10.      * @var RateLimiterFactory
  11.      */
  12.     private $authenticatedApiLimiter;
  13.     public function __construct(RateLimiterFactory $authenticatedApiLimiter)
  14.     {
  15.         $this->authenticatedApiLimiter $authenticatedApiLimiter;
  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('post')) {
  27.             $apiKey $request->headers->get('apikey');
  28.             $authLimiter $this->authenticatedApiLimiter->create($apiKey);
  29.             $authLimiter->reserve(1)->wait();
  30.             if (false === $authLimiter->consume(1)->isAccepted()) {
  31.                 throw new TooManyRequestsHttpException();
  32.             }
  33.         }
  34.         /* $apiKey = $request->headers->get('apikey');
  35.         $limiter = $this->authenticatedApiLimiter->create($apiKey);
  36.         // this blocks the application until the given number of tokens can be consumed
  37.         $limiter->reserve(1)->wait();
  38.         if (false === $limiter->consume(1)->isAccepted()) {
  39.             throw new TooManyRequestsHttpException();
  40.         } */
  41.     }
  42. }