src/Leads/Utils/UtmComponent.php line 45

Open in your IDE?
  1. <?php
  2. namespace App\Leads\Utils;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  7. /**
  8.  * Сохраняет UTM-метки в сессию
  9.  */
  10. class UtmComponent implements EventSubscriberInterface
  11. {
  12.     public const UTM_SOURCE 'utm_source';
  13.     public const UTM_MEDIUM 'utm_medium';
  14.     public const UTM_CONTENT 'utm_content';
  15.     public const UTM_CAMPAIGN 'utm_campaign';
  16.     public const UTM_TERM 'utm_term';
  17.     public const SESSION_KEY 'UTM';
  18.     public const UTM_PARTS = [
  19.         self::UTM_SOURCE,
  20.         self::UTM_MEDIUM,
  21.         self::UTM_CONTENT,
  22.         self::UTM_CAMPAIGN,
  23.         self::UTM_TERM
  24.     ];
  25.     private RequestStack $requestStack;
  26.     public function __construct(RequestStack $requestStack)
  27.     {
  28.         $this->requestStack $requestStack;
  29.         $this->keepUtm();
  30.     }
  31.     protected function getRequest(): ?Request
  32.     {
  33.         return $this->requestStack->getCurrentRequest();
  34.     }
  35.     public function keepUtm(): void
  36.     {
  37.         if (!$this->getRequest()) {
  38.             return;
  39.         }
  40.         $params $this->getRequest()->query->all();
  41.         foreach (self::UTM_PARTS as $part) {
  42.             if (isset($params[$part]) && $params[$part]) {
  43.                 $this->requestStack->getSession()->set($part$params[$part]);
  44.             }
  45.         }
  46.     }
  47.     public function getSessionVar(string $namemixed $default null): mixed
  48.     {
  49.         return $this->requestStack->getSession()->get($name$default);
  50.     }
  51.     public function getUtmSource()
  52.     {
  53.         return $this->getSessionVar(self::UTM_SOURCE);
  54.     }
  55.     public function getUtmMedium()
  56.     {
  57.         return$this->getSessionVar(self::UTM_MEDIUM);
  58.     }
  59.     public function getUtmContent()
  60.     {
  61.         return $this->getSessionVar(self::UTM_CONTENT);
  62.     }
  63.     public function getUtmCampaign()
  64.     {
  65.         return $this->getSessionVar(self::UTM_CAMPAIGN);
  66.     }
  67.     public function getUtmTerm()
  68.     {
  69.         return $this->getSessionVar(self::UTM_TERM);
  70.     }
  71.     public static function getSubscribedEvents()
  72.     {
  73.         return [
  74.             ControllerEvent::class => 'keepUtm'
  75.         ];
  76.     }
  77. }