<?php
namespace App\Component\ReCaptcha\EventSubscriber;
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 ReCaptchaEventSubscriber implements EventSubscriberInterface
{
protected ReCaptcha $reCaptcha;
protected TranslatorInterface $translator;
public function __construct(ReCaptcha $reCaptcha, TranslatorInterface $translator)
{
$this->reCaptcha = $reCaptcha;
$this->translator = $translator;
}
public static function getSubscribedEvents(): array
{
return [
FormEvents::POST_SUBMIT => 'validateReCaptcha',
];
}
public function validateReCaptcha(FormEvent $formEvent)
{
$request = Request::createFromGlobals();
$validation = $this->reCaptcha
->setExpectedHostname($request->getHost())
->verify(
$request->request->get('g-recaptcha-response'),
$request->getClientIp()
)
;
if (!$validation->isSuccess()) {
$formEvent->getForm()->addError(
new FormError($this->translator->trans('recaptcha.message_invalid'))
);
}
}
}