src/Core/Form/EventSubscriber/ReCaptchaValidationSubscriber.php line 44

  1. <?php
  2. declare(strict_types=1);
  3. /**
  4.  * Copyright (c) 2023 TECLA Consulting Group oü.
  5.  * All rights reserved.
  6.  *
  7.  * This unpublished material is proprietary to TECLA Consulting Group oü.
  8.  * All rights reserved. The methods and
  9.  * techniques described herein are considered trade secrets
  10.  * and/or confidential. Reproduction or distribution, in whole
  11.  * or in part, is forbidden except by express written permission
  12.  * of TECLA Consulting Group oü.
  13.  *
  14.  * @author    Matúš Sýkorjak <matus@tecla.no>
  15.  * @copyright 2023 TECLA Consulting Group oü
  16.  */
  17. namespace App\Core\Form\EventSubscriber;
  18. use ReCaptcha\ReCaptcha;
  19. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  20. use Symfony\Component\Form\FormError;
  21. use Symfony\Component\Form\FormEvent;
  22. use Symfony\Component\Form\FormEvents;
  23. use Symfony\Component\HttpFoundation\Request;
  24. final class ReCaptchaValidationSubscriber implements EventSubscriberInterface
  25. {
  26.     private ReCaptcha $reCaptcha;
  27.     public function __construct(ReCaptcha $reCaptcha)
  28.     {
  29.         $this->reCaptcha $reCaptcha;
  30.     }
  31.     public static function getSubscribedEvents(): array
  32.     {
  33.         return [
  34.             FormEvents::POST_SUBMIT => 'onPostSubmit',
  35.         ];
  36.     }
  37.     public function onPostSubmit(FormEvent $event): void
  38.     {
  39.         $request Request::createFromGlobals();
  40.         $result $this->reCaptcha
  41.             ->setExpectedHostname($request->getHost())
  42.             ->verify($request->request->get('g-recaptcha-response'), $request->getClientIp());
  43.         if (!$result->isSuccess()) {
  44.             $event->getForm()->addError(new FormError('The captcha is invalid. Please try again.'));
  45.         }
  46.     }
  47. }