<?php
namespace Nellapp\Bundle\SDKBundle\EventSubscriber;
use Nellapp\Bundle\SDKBundle\Routing\Utils\DomainsRoutingUtils;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\Cookie;
class DeviceIdSubscriber implements EventSubscriberInterface
{
public function __construct(
private DomainsRoutingUtils $domainsRoutingUtils,
)
{
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => 'onResponse',
];
}
public function onResponse(ResponseEvent $event): void
{
$request = $event->getRequest();
if ($request->cookies->has('DEVICE_ID')) {
return;
}
$host = $request->getHost();
$deviceId = bin2hex(random_bytes(16));
$cookie = Cookie::create('DEVICE_ID')
->withValue($deviceId)
->withPath('/')
->withDomain($this->domainsRoutingUtils->getDomain($host))
->withHttpOnly(true)
->withSecure(true)
->withSameSite('lax');
$event->getResponse()->headers->setCookie($cookie);
}
}