src/Form/EventListener/ReCaptchaValidationListener.php line 28

Open in your IDE?
  1. <?php
  2. namespace App\Form\EventListener;
  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. class ReCaptchaValidationListener implements EventSubscriberInterface
  10. {
  11. private ReCaptcha $reCaptcha;
  12. public function __construct(ReCaptcha $reCaptcha)
  13. {
  14. $this->reCaptcha = $reCaptcha;
  15. }
  16. public static function getSubscribedEvents()
  17. {
  18. return [
  19. FormEvents::POST_SUBMIT => 'onPostSubmit'
  20. ];
  21. }
  22. public function onPostSubmit(FormEvent $event)
  23. {
  24. $request = Request::createFromGlobals();
  25. $result = $this->reCaptcha
  26. ->setExpectedHostname($request->getHost())
  27. ->verify($request->request->get('g-recaptcha-response'), $request->getClientIp());
  28. if (!$result->isSuccess()) {
  29. $event->getForm()->addError(new FormError('The captcha is invalid. Please try again.'));
  30. }
  31. }
  32. }