src/EventSubscriber/AntispamSubscriber.php line 42

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\EventSubscriber;
  3. use Psr\Log\LoggerInterface;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\Form\FormEvent;
  6. use Symfony\Component\Form\FormEvents;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. use Symfony\Component\HttpKernel\Exception\HttpException;
  9. class AntispamSubscriber implements EventSubscriberInterface
  10. {
  11.     /**
  12.      * @var LoggerInterface
  13.      */
  14.     private $logger;
  15.     /**
  16.      * @var RequestStack
  17.      */
  18.     private $requestStack;
  19.     public function __construct(
  20.         LoggerInterface $logger,
  21.         RequestStack $requestStack
  22.     )
  23.     {
  24.         $this->logger $logger;
  25.         $this->requestStack $requestStack;
  26.     }
  27.     /**
  28.      * @return array<string>
  29.      */
  30.     public static function getSubscribedEvents(): array
  31.     {
  32.         return [
  33.           FormEvents::PRE_SUBMIT => 'checkContact'
  34.         ];
  35.     }
  36.     public function checkContact(FormEvent $event): void {
  37.         $request $this->requestStack->getCurrentRequest();
  38.         if (!$request){
  39.             return;
  40.         }
  41.         $data $event->getData();
  42.         if (!array_key_exists('phone'$data) || !array_key_exists('faxnumber'$data)){
  43.             throw new HttpException(400"Don't touch my form please");
  44.         }
  45.         [
  46.             'phone' => $phone,
  47.             'faxnumber' => $faxnumber
  48.         ] = $data;
  49.         if ($phone !== "" || $faxnumber !== ""){
  50.             $message "Une potentielle tentative de robot spammeur ayant l'adresse IP suivante '{$request->getClientIp()}' a eu lieu. Le champ phone contenait '{$phone}
  51.             et le champ fax contenait '{$faxnumber}'";
  52.             $this->logger->info($message);
  53.             throw new HttpException(403"Go away dirty bot!");
  54.         }
  55.     }
  56. }