src/Form/Type/ReCaptchaType.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\Form\Type;
  3. use App\Form\EventListener\ReCaptchaValidationListener;
  4. use ReCaptcha\ReCaptcha;
  5. use Symfony\Component\Form\AbstractType;
  6. use Symfony\Component\Form\FormBuilderInterface;
  7. use Symfony\Component\Form\FormInterface;
  8. use Symfony\Component\Form\FormView;
  9. use Symfony\Component\OptionsResolver\OptionsResolver;
  10. use Symfony\Contracts\Translation\TranslatorInterface;
  11. /**
  12.  * Class ReCaptchaType.
  13.  *
  14.  * @see https://medium.com/@qferrer/securing-your-symfony-forms-with-google-recaptcha-v2-dbfc902b0c50
  15.  *
  16.  */
  17. class ReCaptchaType extends AbstractType
  18. {
  19.     /**
  20.      * @var \ReCaptcha\ReCaptcha
  21.      */
  22.     private $reCaptcha;
  23.     /**
  24.      * @var \Symfony\Contracts\Translation\TranslatorInterface
  25.      */
  26.     protected $translator;
  27.     /**
  28.      * ReCaptchaType constructor.
  29.      *
  30.      * @param ReCaptcha $reCaptcha
  31.      */
  32.     public function __construct(ReCaptcha $reCaptchaTranslatorInterface $translator)
  33.     {
  34.         $this->reCaptcha $reCaptcha;
  35.         $this->translator $translator;
  36.     }
  37.     /**
  38.      * @inheritDoc
  39.      */
  40.     public function buildForm(FormBuilderInterface $builder, array $options)
  41.     {
  42.       if($_ENV['USE_CAPTCHA']) {
  43.         $subscriber = new ReCaptchaValidationListener($this->reCaptcha$this->translator);
  44.         $subscriber->setInvalidMessage($options['invalid_message']);
  45.         $builder->addEventSubscriber($subscriber);
  46.       }
  47.     }
  48.     /**
  49.      * @inheritDoc
  50.      */
  51.     public function buildView(FormView $viewFormInterface $form, array $options)
  52.     {
  53.         $view->vars['type'] = $options['type'];
  54.     }
  55.     /**
  56.      * @inheritDoc
  57.      */
  58.     public function configureOptions(OptionsResolver $resolver)
  59.     {
  60.         $resolver
  61.             ->setDefault('type''invisible')
  62.             ->setDefault('invalid_message''error.form.captcha_invalid')
  63.             ->setAllowedValues('type', ['checkbox''invisible']);
  64.     }
  65. }