src/Subscriber/IpBannedSubscriber.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\Subscriber;
  3. use App\EntityManager\UserIpBannedManager;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class IpBannedSubscriber implements EventSubscriberInterface
  11. {
  12.     private $twig;
  13.     private $userIpBannedManager;
  14.     public function __construct(
  15.         \Twig\Environment $twig,
  16.         UserIpBannedManager $userIpBannedManager
  17.     )
  18.     {
  19.         $this->twig $twig;
  20.         $this->userIpBannedManager $userIpBannedManager;
  21.     }
  22.     public function onKernelEvent(RequestEvent $event)
  23.     {
  24.         if (!$event->isMasterRequest() || $event->getRequest()->attributes->get('_route') == 'fos_js_routing_js') {
  25.             return;
  26.         }
  27.         if ($event instanceof ExceptionEvent) {
  28.             $throwable $event->getThrowable();
  29.             // only process 404s
  30.             if (!$throwable instanceof NotFoundHttpException) {
  31.                 return;
  32.             }
  33.         }
  34.         $request $event->getRequest();
  35.         if ($this->userIpBannedManager->checkBan($request)) {
  36.             $html $this->twig->render('page/bannedip.html.twig', ['ip' => $request->getClientIp()]);
  37.             $response = new Response($html403);
  38.             $event->setResponse($response);
  39.         }
  40.     }
  41.     public static function getSubscribedEvents()
  42.     {
  43.         return [
  44.             KernelEvents::REQUEST => 'onKernelEvent',
  45.             KernelEvents::EXCEPTION => 'onKernelEvent',
  46.         ];
  47.     }
  48. }