src/EventSubscriber/IpRestrictionSubscriber.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. class IpRestrictionSubscriber implements EventSubscriberInterface
  8. {
  9.     /**
  10.      * IpRestrictionSubscriber constructor.
  11.      */
  12.     public function __construct(
  13.         private string $allowedIps ''
  14.     ) {
  15.     }
  16.     public function onKernelRequest(RequestEvent $event): void
  17.     {
  18.         $request $event->getRequest();
  19.         $currentIp $request->getClientIp();
  20.         $allowedIps explode(','$this->allowedIps);
  21.         if (is_countable($allowedIps) && '' != $allowedIps[0] && !in_array($currentIp$allowedIps)) {
  22.             $event->setResponse(new Response('You are not allowed here !'Response::HTTP_FORBIDDEN));
  23.         }
  24.     }
  25.     public static function getSubscribedEvents(): array
  26.     {
  27.         return [
  28.             KernelEvents::REQUEST => [['onKernelRequest'1]],
  29.         ];
  30.     }
  31. }