<?php
namespace App\Leads\Utils;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
/**
* Сохраняет UTM-метки в сессию
*/
class UtmComponent implements EventSubscriberInterface
{
public const UTM_SOURCE = 'utm_source';
public const UTM_MEDIUM = 'utm_medium';
public const UTM_CONTENT = 'utm_content';
public const UTM_CAMPAIGN = 'utm_campaign';
public const UTM_TERM = 'utm_term';
public const SESSION_KEY = 'UTM';
public const UTM_PARTS = [
self::UTM_SOURCE,
self::UTM_MEDIUM,
self::UTM_CONTENT,
self::UTM_CAMPAIGN,
self::UTM_TERM
];
private RequestStack $requestStack;
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
$this->keepUtm();
}
protected function getRequest(): ?Request
{
return $this->requestStack->getCurrentRequest();
}
public function keepUtm(): void
{
if (!$this->getRequest()) {
return;
}
$params = $this->getRequest()->query->all();
foreach (self::UTM_PARTS as $part) {
if (isset($params[$part]) && $params[$part]) {
$this->requestStack->getSession()->set($part, $params[$part]);
}
}
}
public function getSessionVar(string $name, mixed $default = null): mixed
{
return $this->requestStack->getSession()->get($name, $default);
}
public function getUtmSource()
{
return $this->getSessionVar(self::UTM_SOURCE);
}
public function getUtmMedium()
{
return$this->getSessionVar(self::UTM_MEDIUM);
}
public function getUtmContent()
{
return $this->getSessionVar(self::UTM_CONTENT);
}
public function getUtmCampaign()
{
return $this->getSessionVar(self::UTM_CAMPAIGN);
}
public function getUtmTerm()
{
return $this->getSessionVar(self::UTM_TERM);
}
public static function getSubscribedEvents()
{
return [
ControllerEvent::class => 'keepUtm'
];
}
}