<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class IpRestrictionSubscriber implements EventSubscriberInterface
{
/**
* IpRestrictionSubscriber constructor.
*/
public function __construct(
private string $allowedIps = ''
) {
}
public function onKernelRequest(RequestEvent $event): void
{
$request = $event->getRequest();
$currentIp = $request->getClientIp();
$allowedIps = explode(',', $this->allowedIps);
if (is_countable($allowedIps) && '' != $allowedIps[0] && !in_array($currentIp, $allowedIps)) {
$event->setResponse(new Response('You are not allowed here !', Response::HTTP_FORBIDDEN));
}
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 1]],
];
}
}