<?php
namespace App\Form\EventListener;
use ReCaptcha\ReCaptcha;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Contracts\Translation\TranslatorInterface;
class ReCaptchaValidatorListener implements EventSubscriberInterface
{
public function __construct(ReCaptcha $recaptcha, TranslatorInterface $translator, bool $enabled)
{
$this->recaptcha = $recaptcha;
$this->translator = $translator;
$this->enabled = $enabled;
}
public static function getSubscribedEvents()
{
return [
FormEvents::POST_SUBMIT => 'onPostSubmit'
];
}
public function onPostSubmit(FormEvent $event)
{
// No hacer nada si no está habilitado
if (! $this->enabled)
return;
// Comprobación de que es válido
$request = Request::createFromGlobals();
$result =$this->recaptcha
->setExpectedHostname($request->getHost())
->verify($request->get('g-recaptcha-response'), $request->getClientIp());
if (! $result->isSuccess())
$event->getForm()->addError(new FormError($this->translator->trans("El captcha no es válido, por favor inténtelo de nuevo.")));
}
}
?>