<?php
declare(strict_types=1);
namespace App\EventListener;
use App\Request\DeferredCookieInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class DeferredCookieListener implements EventSubscriberInterface
{
protected DeferredCookieInterface $cookieManager;
public function __construct(DeferredCookieInterface $cookieManager)
{
$this->cookieManager = $cookieManager;
}
public function onKernelResponse(ResponseEvent $event)
{
$headers = $event->getResponse()->headers;
/** @var Cookie $cookie */
foreach ($this->cookieManager->getDeferred() as $cookie)
$headers->setCookie($cookie);
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::RESPONSE => ['onKernelResponse', 0],
];
}
}