|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This source file is available under two different licenses: |
| 5 | + * - GNU General Public License version 3 (GPLv3) |
| 6 | + * - DACHCOM Commercial License (DCL) |
| 7 | + * Full copyright and license information is available in |
| 8 | + * LICENSE.md which is distributed with this source code. |
| 9 | + * |
| 10 | + * @copyright Copyright (c) DACHCOM.DIGITAL AG (https://www.dachcom-digital.com) |
| 11 | + * @license GPLv3 and DCL |
| 12 | + */ |
| 13 | + |
| 14 | +namespace FormBuilderBundle\Form\Type; |
| 15 | + |
| 16 | +use FormBuilderBundle\Tool\MathCaptchaProcessor; |
| 17 | +use FormBuilderBundle\Validator\Constraints\MathCaptcha; |
| 18 | +use Symfony\Component\Form\AbstractType; |
| 19 | +use Symfony\Component\Form\Extension\Core\Type\HiddenType; |
| 20 | +use Symfony\Component\Form\Extension\Core\Type\TextType; |
| 21 | +use Symfony\Component\Form\FormBuilderInterface; |
| 22 | +use Symfony\Component\Form\FormInterface; |
| 23 | +use Symfony\Component\Form\FormView; |
| 24 | +use Symfony\Component\OptionsResolver\OptionsResolver; |
| 25 | + |
| 26 | +final class MathCaptchaType extends AbstractType |
| 27 | +{ |
| 28 | + public function __construct(protected MathCaptchaProcessor $mathCaptchaProcessor) |
| 29 | + { |
| 30 | + } |
| 31 | + |
| 32 | + public function buildForm(FormBuilderInterface $builder, array $options): void |
| 33 | + { |
| 34 | + $stamp = $this->mathCaptchaProcessor->generateStamp(); |
| 35 | + $challenge = $this->mathCaptchaProcessor->generateChallenge($options['difficulty'], $stamp); |
| 36 | + |
| 37 | + $challengeFieldOptions = [ |
| 38 | + 'label' => $challenge['user_challenge'], |
| 39 | + 'label_attr' => [ |
| 40 | + 'class' => 'math-captcha-challenge-label' |
| 41 | + ], |
| 42 | + ]; |
| 43 | + |
| 44 | + if ($challenge['hash'] === null) { |
| 45 | + $challengeFieldOptions['attr']['disabled'] = true; |
| 46 | + $challengeFieldOptions['label'] = 'No encryption secret found. cannot create challenge.'; |
| 47 | + } |
| 48 | + |
| 49 | + $builder->add('challenge', TextType::class, $challengeFieldOptions); |
| 50 | + $builder->add('hash', HiddenType::class, ['data' => $challenge['hash']]); |
| 51 | + $builder->add('stamp', HiddenType::class, ['data' => $stamp]); |
| 52 | + } |
| 53 | + |
| 54 | + public function buildView(FormView $view, FormInterface $form, array $options): void |
| 55 | + { |
| 56 | + $view->vars['attr']['class'] = 'math-captcha'; |
| 57 | + } |
| 58 | + |
| 59 | + public function getBlockPrefix(): string |
| 60 | + { |
| 61 | + return 'form_builder_math_captcha_type'; |
| 62 | + } |
| 63 | + |
| 64 | + public function configureOptions(OptionsResolver $resolver): void |
| 65 | + { |
| 66 | + $resolver->setDefaults([ |
| 67 | + 'mapped' => false, |
| 68 | + 'difficulty' => 'easy', |
| 69 | + 'constraints' => [new MathCaptcha()], |
| 70 | + ]); |
| 71 | + } |
| 72 | +} |
0 commit comments