src/Controller/HomeController.php line 73

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Newsletter;
  4. use App\Form\Type\NewsletterType;
  5. use Doctrine\DBAL\Exception;
  6. use Doctrine\Persistence\ManagerRegistry;
  7. use phpDocumentor\Reflection\Types\Mixed_;
  8. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  9. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  10. use Symfony\Component\HttpFoundation\Request;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpKernel\EventListener\AbstractSessionListener;
  13. use Symfony\Component\Routing\Annotation\Route;
  14. use Google\Cloud\RecaptchaEnterprise\V1\RecaptchaEnterpriseServiceClient;
  15. use Google\Cloud\RecaptchaEnterprise\V1\Event;
  16. use Google\Cloud\RecaptchaEnterprise\V1\Assessment;
  17. use Google\Cloud\RecaptchaEnterprise\V1\TokenProperties\InvalidReason;
  18. class HomeController extends AbstractController
  19. {
  20.     /**
  21.      * @var ParameterBagInterface
  22.      */
  23.     private $params;
  24.     public function __construct(ParameterBagInterface $params)
  25.     {
  26.         $this->params $params;
  27.     }
  28.     /**
  29.      * @Route("/", name="index")
  30.      * @param Request $request
  31.      * @return Response
  32.      */
  33.     public function index(Request $request): Response
  34.     {
  35.         $page $request->get('page'null);
  36.         if($page === 'beta') {
  37.             return $this->render('home/beta.html.twig', [
  38.             ]);
  39.         } else {
  40.             // creates a task object and initializes some data for this example
  41.             $newsletter = new Newsletter();
  42.             $form $this->createForm(NewsletterType::class, $newsletter, [
  43.                 'action' => $this->generateUrl('thank_you'),
  44.                 'method' => 'POST'
  45.             ]);
  46.             $response $this->render('home/index.html.twig', [
  47.                 'form' => $form->createView()
  48.             ]);
  49.             $response->setPublic();
  50.             $response->setMaxAge(2500000);
  51.             $response->headers->addCacheControlDirective('must-revalidate'true);
  52.             $response->headers->set(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER'true');
  53.             return $response;
  54.         }
  55.     }
  56.     /**
  57.      * @Route("/trading-strategy-algorithm-that-will-work-at-any-time", name="trading_strategy_text")
  58.      */
  59.     public function tradingStrategyText(): Response
  60.     {
  61.         return $this->render('home/trading-strategy-text.html.twig', [
  62.         ]);
  63.     }
  64.     /**
  65.      * @Route("/privacy-policy", name="privacy_policy")
  66.      */
  67.     public function privacyPolicy(): Response
  68.     {
  69.         return $this->render('home/privacy-policy.html.twig', [
  70.         ]);
  71.     }
  72.     /**
  73.      * @Route("/thank-you", name="thank_you")
  74.      * @param Request $request
  75.      * @param ManagerRegistry $registry
  76.      * @return Response
  77.      */
  78.     public function thankYou(Request $requestManagerRegistry $registry): Response
  79.     {
  80.         $error false;
  81.         $duplicate false;
  82.         // just set up a fresh $task object (remove the example data)
  83.         $newsletter = new Newsletter();
  84.         $form $this->createForm(NewsletterType::class, $newsletter);
  85.         $form->handleRequest($request);
  86.         if ($form->isSubmitted() && $form->isValid()) {
  87.             // $form->getData() holds the submitted values
  88.             // but, the original `$task` variable has also been updated
  89.             $newsletter $form->getData();
  90.             $newsletter->setCreatedAt(new \DateTimeImmutable('now'));
  91.             $newsletter->setIp($_SERVER['REMOTE_ADDR']);
  92. //            dump($newsletter);
  93.             $recaptcha_response $request->get('g-recaptcha-response');
  94. //            dump($recaptcha_response);
  95. //            $score = $this->create_assessment(
  96. //                '6LeRJt0eAAAAAMYqufqaweCRDb0fDBLm_ub20maZ',
  97. //                $recaptcha_response,
  98. //                'ntnewsletter'
  99. //            );
  100. //            dump('This is score in TY controller', $score);
  101.             try {
  102.                 $entityManager $registry->getManager();
  103.                 $entityManager->persist($newsletter);
  104.                 $entityManager->flush();
  105.             } catch (Exception\UniqueConstraintViolationException $exception) {
  106. //                dump($exception);
  107.                 $duplicate true;
  108.             } catch (\Exception $exception) {
  109.                 $error true;
  110.             }
  111.             return $this->render('home/thank-you.html.twig', [
  112.                 'form' => $form,
  113.                 'error' => $error,
  114.                 'duplicate' => $duplicate
  115.             ]);
  116.         } else {
  117.             return $this->redirectToRoute('index');
  118.         }
  119.     }
  120.     /**
  121.      * Create an assessment to analyze the risk of a UI action.
  122.      * @param string $siteKey The key ID for the reCAPTCHA key (See https://cloud.google.com/recaptcha-enterprise/docs/create-key)
  123.      * @param string $token The user's response token for which you want to receive a reCAPTCHA score. (See https://cloud.google.com/recaptcha-enterprise/docs/create-assessment#retrieve_token)
  124.      * @param string $project Your Google Cloud project ID
  125.      * @return null|mixed
  126.      */
  127.     function create_assessment(string $siteKeystring $tokenstring $project) {
  128.         $score null;
  129.         // TODO: To avoid memory issues, move this client generation outside
  130.         // of this example, and cache it (recommended) or call client.close()
  131.         // before exiting this method.
  132.         $client = new RecaptchaEnterpriseServiceClient();
  133.         $projectName $client->projectName($project);
  134.         $event = (new Event())
  135.             ->setSiteKey($siteKey)
  136.             ->setToken($token);
  137.         $assessment = (new Assessment())
  138.             ->setEvent($event);
  139.         try {
  140.             $response $client->createAssessment(
  141.                 $projectName,
  142.                 $assessment
  143.             );
  144.             // You can use the score only if the assessment is valid,
  145.             // In case of failures like re-submitting the same token, getValid() will return false
  146.             if ($response->getTokenProperties()->getValid() == false) {
  147.                 dump('The CreateAssessment() call failed because the token was invalid for the following reason: ');
  148.                 dump(InvalidReason::name($response->getTokenProperties()->getInvalidReason()));
  149.             } else {
  150.                 dump('The score for the protection action is:');
  151.                 $score $response->getRiskAnalysis()->getScore();
  152.                 // Optional: You can use the following methods to get more data about the token
  153.                 // Action name provided at token generation.
  154.                 // printf($response->getTokenProperties()->getAction() . PHP_EOL);
  155.                 // The timestamp corresponding to the generation of the token.
  156.                 // printf($response->getTokenProperties()->getCreateTime()->getSeconds() . PHP_EOL);
  157.                 // The hostname of the page on which the token was generated.
  158.                 // printf($response->getTokenProperties()->getHostname() . PHP_EOL);
  159.             }
  160.         } catch (\Exception $e) {
  161.             dump('CreateAssessment() call failed with the following error: ');
  162.             dump($e);
  163.         }
  164.         return $score;
  165.     }
  166. }