src/Form/EventListener/ReCaptchaValidationListener.php line 36

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;
  12. private $invalidMessage = 'The captcha is invalid.';
  13. public function __construct(ReCaptcha $reCaptcha)
  14. {
  15. $this->reCaptcha = $reCaptcha;
  16. }
  17. public static function getSubscribedEvents()
  18. {
  19. return [
  20. FormEvents::POST_SUBMIT => 'onPostSubmit',
  21. ];
  22. }
  23. public function setInvalidMessage($message)
  24. {
  25. $this->invalidMessage = $message;
  26. return $this;
  27. }
  28. public function onPostSubmit(FormEvent $event)
  29. {
  30. $request = Request::createFromGlobals();
  31. $result = $this->reCaptcha
  32. ->setExpectedHostname($request->getHost())
  33. ->verify($request->request->get('g-recaptcha-response'), $request->getClientIp());
  34. if (!$result->isSuccess()) {
  35. $event->getForm()->addError(new FormError($this->invalidMessage));
  36. }
  37. }
  38. }