1 <?php
declare(strict_types
=1);
4 * This file is part of the Rapsys PackBundle package.
6 * (c) Raphaël Gertz <symfony@rapsys.eu>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Rapsys\PackBundle\Form
;
14 use Rapsys\PackBundle\Util\ImageUtil
;
15 use Rapsys\PackBundle\Util\SluggerUtil
;
17 use Symfony\Contracts\Translation\TranslatorInterface
;
18 use Symfony\Component\Form\AbstractType
;
19 use Symfony\Component\Form\Extension\Core\Type\HiddenType
;
20 use Symfony\Component\Form\Extension\Core\Type\IntegerType
;
21 use Symfony\Component\Form\FormBuilderInterface
;
22 use Symfony\Component\Form\FormEvents
;
23 use Symfony\Component\Form\FormEvent
;
24 use Symfony\Component\Form\FormError
;
27 * Captcha Type class definition
29 * @see https://symfony.com/doc/current/form/create_custom_field_type.html
31 class CaptchaType
extends AbstractType
{
35 * @param ImageUtil $image
36 * @param SluggerUtil $slugger
37 * @param TranslatorInterface $translator The translator instance
39 public function __construct(protected ImageUtil
$image, protected SluggerUtil
$slugger, protected TranslatorInterface
$translator) {
47 public function buildForm(FormBuilderInterface
$builder, array $options): void {
49 $captcha = $this->image
->getCaptcha((new \
DateTime('-1 year'))->getTimestamp());
52 $builder->add('_captcha_token', HiddenType
::class, ['data' => $captcha['token'], 'empty_data' => $captcha['token']]);
55 $builder->add('captcha', IntegerType
::class, ['label_attr' => ['class' => 'captcha'], 'label' => '<img src="'.htmlentities($captcha['src']).'" alt="'.htmlentities($captcha['equation']).'" />', 'label_html' => true, 'translation_domain' => false]);
57 //Add event listener on captcha
58 $builder->addEventListener(FormEvents
::PRE_SUBMIT
, [$this, 'validateCaptcha']);
64 * @param FormEvent $event The form event
66 public function validateCaptcha(FormEvent
$event): void {
68 $form = $event->getForm();
71 $data = $event->getData();
74 $token = $form->get('_captcha_token')->getConfig()->getData();
77 if (empty($data['captcha'])) {
78 //Add error on captcha
79 $form->addError(new FormError($this->translator
->trans('Captcha is empty')));
82 $data['_captcha_token'] = $token;
85 $event->setData($data);
86 //With invalid captcha
87 } elseif ($this->slugger
->hash($data['captcha']) !== $data['_captcha_token']) {
88 //Add error on captcha
89 $form->addError(new FormError($this->translator
->trans('Captcha is invalid')));
92 $data['_captcha_token'] = $token;
95 $event->setData($data);