src/Component/ReCaptcha/EventSubscriber/ReCaptchaEventSubscriber.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\Component\ReCaptcha\EventSubscriber;
  3. use ReCaptcha\ReCaptcha;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\Form\FormError;
  6. use Symfony\Component\Form\FormEvent;
  7. use Symfony\Component\Form\FormEvents;
  8. use Symfony\Component\HttpFoundation\Request;
  9. use Symfony\Contracts\Translation\TranslatorInterface;
  10. class ReCaptchaEventSubscriber implements EventSubscriberInterface
  11. {
  12.     protected ReCaptcha $reCaptcha;
  13.     protected TranslatorInterface $translator;
  14.     public function __construct(ReCaptcha $reCaptchaTranslatorInterface $translator)
  15.     {
  16.         $this->reCaptcha $reCaptcha;
  17.         $this->translator $translator;
  18.     }
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             FormEvents::POST_SUBMIT => 'validateReCaptcha',
  23.         ];
  24.     }
  25.     public function validateReCaptcha(FormEvent $formEvent)
  26.     {
  27.         $request Request::createFromGlobals();
  28.         $validation $this->reCaptcha
  29.             ->setExpectedHostname($request->getHost())
  30.             ->verify(
  31.                 $request->request->get('g-recaptcha-response'),
  32.                 $request->getClientIp()
  33.             )
  34.         ;
  35.         if (!$validation->isSuccess()) {
  36.             $formEvent->getForm()->addError(
  37.                 new FormError($this->translator->trans('recaptcha.message_invalid'))
  38.             );
  39.         }
  40.     }
  41. }