vendor/gregwar/captcha-bundle/Controller/CaptchaController.php line 42

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Gregwar\CaptchaBundle\Controller;
  4. use Gregwar\CaptchaBundle\Generator\CaptchaGenerator;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. /**
  8.  * Generates a captcha via a URL.
  9.  *
  10.  * @author Jeremy Livingston <jeremy.j.livingston@gmail.com>
  11.  */
  12. class CaptchaController
  13. {
  14.     /** @var CaptchaGenerator */
  15.     private $captchaGenerator;
  16.     /** @var array<mixed> */
  17.     private $config;
  18.     /**
  19.      * CaptchaController constructor.
  20.      *
  21.      * @param CaptchaGenerator  $captchaGenerator
  22.      * @param array<mixed>      $config
  23.      */
  24.     public function __construct(CaptchaGenerator $captchaGenerator, array $config)
  25.     {
  26.         $this->captchaGenerator $captchaGenerator;
  27.         $this->config $config;
  28.     }
  29.     public function generateCaptchaAction(Request $requeststring $key): Response
  30.     {
  31.         $session $request->getSession();
  32.         $whitelistKey $this->config['whitelist_key'];
  33.         $isOk false;
  34.         if ($session->has($whitelistKey)) {
  35.             $keys $session->get($whitelistKey);
  36.             if (is_array($keys) && in_array($key$keys)) {
  37.                 $isOk true;
  38.             }
  39.         }
  40.         if (!$isOk) {
  41.             return $this->error($this->config);
  42.         }
  43.         $persistedOptions $session->get($key, array());
  44.         $options array_merge($this->config$persistedOptions);
  45.         $phrase $this->captchaGenerator->getPhrase($options);
  46.         $this->captchaGenerator->setPhrase($phrase);
  47.         $persistedOptions['phrase'] = $phrase;
  48.         $session->set($key$persistedOptions);
  49.         $response = new Response($this->captchaGenerator->generate($options));
  50.         $response->headers->set('Content-type''image/jpeg');
  51.         $response->headers->set('Pragma''no-cache');
  52.         $response->headers->set('Cache-Control''no-cache');
  53.         return $response;
  54.     }
  55.     /**
  56.      * @param array<mixed> $options
  57.      *
  58.      * @return Response
  59.      */
  60.     private function error(array $options): Response
  61.     {
  62.         $this->captchaGenerator->setPhrase('');
  63.         $response = new Response($this->captchaGenerator->generate($options));
  64.         $response->setStatusCode(428);
  65.         $response->headers->set('Content-type''image/jpeg');
  66.         $response->headers->set('Pragma''no-cache');
  67.         $response->headers->set('Cache-Control''no-cache');
  68.         return $response;
  69.     }
  70. }