<?php
namespace App\Component\Utm\EventSubscriber;
use App\Component\Configuration\Util\Config;
use App\Component\Utm\UtmConstants;
use App\Event\ApplicantEvent;
use App\Service\UtmService;
use JetBrains\PhpStorm\ArrayShape;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class UtmRequestEventSubscriber implements EventSubscriberInterface
{
private array $utm = [];
private ?Request $requestContext = null;
public function __construct(protected Config $config)
{
}
#[ArrayShape([KernelEvents::REQUEST => 'string', KernelEvents::RESPONSE => 'string', ApplicantEvent::EVENT_PRE_PERSIST => 'string'])]
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => 'onRequest',
KernelEvents::RESPONSE => 'onResponse',
ApplicantEvent::EVENT_PRE_PERSIST => 'applicantPrePersist',
];
}
public function onRequest(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$utm = UtmService::getUtmArrayFromRequest();
$this->requestContext = $event->getRequest();
if (empty($utm)) {
return;
}
$this->utm = $utm;
}
public function onResponse(ResponseEvent $event)
{
if (empty($this->utm)) {
return;
}
$lifetime = $this->config->get('utm_cookie_lifetime');
$event->getResponse()->headers->setCookie(UtmService::createUtmCookie($this->utm, $lifetime));
}
public function applicantPrePersist(ApplicantEvent $applicantEvent)
{
$utmCookie = $this->requestContext?->cookies->get(UtmConstants::COOKIE_ID);
if (empty($utmCookie)) {
return;
}
try {
$utm = json_decode($utmCookie, true, 512, \JSON_THROW_ON_ERROR);
} catch (\Exception) {
$utm = [];
}
$applicantEvent->getApplicant()->setUtm($utm);
}
}