<?php
namespace App\Subscriber;
use App\EntityManager\UserIpBannedManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class IpBannedSubscriber implements EventSubscriberInterface
{
private $twig;
private $userIpBannedManager;
public function __construct(
\Twig\Environment $twig,
UserIpBannedManager $userIpBannedManager
)
{
$this->twig = $twig;
$this->userIpBannedManager = $userIpBannedManager;
}
public function onKernelEvent(RequestEvent $event)
{
if (!$event->isMasterRequest() || $event->getRequest()->attributes->get('_route') == 'fos_js_routing_js') {
return;
}
if ($event instanceof ExceptionEvent) {
$throwable = $event->getThrowable();
// only process 404s
if (!$throwable instanceof NotFoundHttpException) {
return;
}
}
$request = $event->getRequest();
if ($this->userIpBannedManager->checkBan($request)) {
$html = $this->twig->render('page/bannedip.html.twig', ['ip' => $request->getClientIp()]);
$response = new Response($html, 403);
$event->setResponse($response);
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => 'onKernelEvent',
KernelEvents::EXCEPTION => 'onKernelEvent',
];
}
}