<?php declare(strict_types=1);
namespace Acris\CookieConsent\Subscriber;
use Acris\CookieConsent\Components\CookieService;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\Event\BeforeSendResponseEvent;
use Shopware\Core\PlatformRequest;
use Shopware\Storefront\Framework\Routing\StorefrontResponse;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
class BeforeResponseSendSubscriber implements EventSubscriberInterface
{
private CookieService $cookieService;
public function __construct(CookieService $cookieService)
{
$this->cookieService = $cookieService;
}
public static function getSubscribedEvents()
{
return [
BeforeSendResponseEvent::class => 'setFunctionalCookiesWithValue',
];
}
public function setFunctionalCookiesWithValue(BeforeSendResponseEvent $responseEvent): void
{
$request = $responseEvent->getRequest();
$response = $responseEvent->getResponse();
if ($response instanceof StorefrontResponse) {
if ($request->attributes->has(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID)) {
$context = Context::createDefaultContext();
$defaultCookies = $this->cookieService->getDefaultCookies($request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID), $context);
$requestCookies = $request->cookies->all();
if (!empty($defaultCookies)) {
foreach ($defaultCookies as $cookieEntity) {
if (empty($requestCookies) || !empty($requestCookies) && !array_key_exists($cookieEntity->getCookieId(), $requestCookies)) {
$response->headers->setCookie(new Cookie($cookieEntity->getCookieId(), $cookieEntity->getDefaultValue(), time() + (86400 * 30), '/', null, false, false));
}
}
}
}
}
}
}