src/Component/Utm/EventSubscriber/UtmRequestEventSubscriber.php line 58

Open in your IDE?
  1. <?php
  2. namespace App\Component\Utm\EventSubscriber;
  3. use App\Component\Configuration\Util\Config;
  4. use App\Component\Utm\UtmConstants;
  5. use App\Event\ApplicantEvent;
  6. use App\Service\UtmService;
  7. use JetBrains\PhpStorm\ArrayShape;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. use Symfony\Component\HttpKernel\Event\RequestEvent;
  11. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  12. use Symfony\Component\HttpKernel\KernelEvents;
  13. class UtmRequestEventSubscriber implements EventSubscriberInterface
  14. {
  15.     private array $utm = [];
  16.     private ?Request $requestContext null;
  17.     public function __construct(protected Config $config)
  18.     {
  19.     }
  20.     #[ArrayShape([KernelEvents::REQUEST => 'string'KernelEvents::RESPONSE => 'string'ApplicantEvent::EVENT_PRE_PERSIST => 'string'])]
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [
  24.             KernelEvents::REQUEST => 'onRequest',
  25.             KernelEvents::RESPONSE => 'onResponse',
  26.             ApplicantEvent::EVENT_PRE_PERSIST => 'applicantPrePersist',
  27.         ];
  28.     }
  29.     public function onRequest(RequestEvent $event)
  30.     {
  31.         if (!$event->isMainRequest()) {
  32.             return;
  33.         }
  34.         $utm UtmService::getUtmArrayFromRequest();
  35.         $this->requestContext $event->getRequest();
  36.         if (empty($utm)) {
  37.             return;
  38.         }
  39.         $this->utm $utm;
  40.     }
  41.     public function onResponse(ResponseEvent $event)
  42.     {
  43.         if (empty($this->utm)) {
  44.             return;
  45.         }
  46.         $lifetime $this->config->get('utm_cookie_lifetime');
  47.         $event->getResponse()->headers->setCookie(UtmService::createUtmCookie($this->utm$lifetime));
  48.     }
  49.     public function applicantPrePersist(ApplicantEvent $applicantEvent)
  50.     {
  51.         $utmCookie $this->requestContext?->cookies->get(UtmConstants::COOKIE_ID);
  52.         if (empty($utmCookie)) {
  53.             return;
  54.         }
  55.         try {
  56.             $utm json_decode($utmCookietrue512\JSON_THROW_ON_ERROR);
  57.         } catch (\Exception) {
  58.             $utm = [];
  59.         }
  60.         $applicantEvent->getApplicant()->setUtm($utm);
  61.     }
  62. }