<?php
declare(strict_types=1);
namespace App\Component\Captcha\EventSubscriber;
use App\Component\Captcha\CaptchaFactory;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Form\FormError;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Symfony\Contracts\Translation\TranslatorInterface;
class CaptchaEventSubscriber implements EventSubscriberInterface
{
public function __construct(
private readonly CaptchaFactory $factory,
private readonly TranslatorInterface $translator
) {
}
public static function getSubscribedEvents(): array
{
return [
FormEvents::POST_SUBMIT => 'validateCaptcha',
];
}
public function validateCaptcha(FormEvent $formEvent): void
{
if (!$this->factory->create()->isSuccess()) {
$formEvent->getForm()->addError(
new FormError($this->translator->trans(id: 'captcha.message_invalid', domain: 'messages'))
);
}
}
}