<?php
namespace Boldr\Cms\CmsBundle\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\{ RequestEvent, ResponseEvent };
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpFoundation\{ Request, Cookie };
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Boldr\Cms\CmsBundle\Cookies\CookieManager;
class CookieSubscriber implements EventSubscriberInterface
{
const COOKIE_NAME = 'boldr_cms_cookie_preferences';
private ParameterBagInterface $parameterBag;
private CookieManager $cookieManager;
public function __construct(ParameterBagInterface $parameterBag, CookieManager $cookieManager)
{
$this->cookieManager = $cookieManager;
$this->parameterBag = $parameterBag;
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 20]],
KernelEvents::RESPONSE => [['onKernelResponse']],
];
}
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
$preferences = $this->parseCookieOptions($request);
$this->cookieManager->setAcceptsMarketingCookies($preferences['marketing_cookies']);
$this->cookieManager->setAcceptsAnalysisCookies($preferences['analysis_cookies']);
$this->cookieManager->setAcceptsPreferenceCookies($preferences['preference_cookies']);
if ($preferences['set'])
{
$this->cookieManager->markAsSet();
}
}
public function onKernelResponse(ResponseEvent $event)
{
$response = $event->getResponse();
if (!$this->cookieManager->isSet())
{
return;
}
$newPreferences = [
'marketing_cookies' => $this->cookieManager->getAcceptsMarketingCookies(),
'analysis_cookies' => $this->cookieManager->getAcceptsAnalysisCookies(),
'preference_cookies' => $this->cookieManager->getAcceptsPreferenceCookies()
];
$cookiePreferences = $this->parseCookieOptions($event->getRequest());
if ($newPreferences !== $cookiePreferences)
{
$cookie = new Cookie(self::COOKIE_NAME, implode(',', array_keys(array_filter($newPreferences))), strtotime('next year'), '/', null, null, false);
$response->headers->setCookie($cookie);
}
}
private function parseCookieOptions(Request $request): array
{
$preferences = [
'marketing_cookies' => false,
'analysis_cookies' => false,
'preference_cookies' => false,
'set' => false
];
if ($request->cookies->has(self::COOKIE_NAME))
{
$preferences['set'] = true;
$parts = explode(',', $request->cookies->get(self::COOKIE_NAME));
foreach ($parts as $part)
{
$preferences[trim($part)] = true;
}
}
return $preferences;
}
}