<?php declare(strict_types=1);
namespace Bpa\VideoIframeCookieHandler\Subscriber;
use Bpa\VideoIframeCookieHandler\BpaPlatformVideoIframeCookieHandler;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Event\StorefrontRenderEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class FilterCookiesSubscriber implements EventSubscriberInterface
{
/**
* @var SystemConfigService
*/
private SystemConfigService $systemConfigService;
/**
* @param SystemConfigService $systemConfigService
*/
public function __construct(SystemConfigService $systemConfigService)
{
$this->systemConfigService = $systemConfigService;
}
/**
* @return string[]
*/
public static function getSubscribedEvents(): array
{
return [
StorefrontRenderEvent::class => 'onStorefrontRender',
];
}
/**
* @param StorefrontRenderEvent $event
* @return void
*/
public function onStorefrontRender(StorefrontRenderEvent $event)
{
$parameters = $event->getParameters();
$salesChannelContext = $event->getSalesChannelContext();
if (array_key_exists('cookieGroups', $parameters)) {
$cookieGroups = $this->filterIframeCookie($salesChannelContext->getSalesChannelId(), $parameters['cookieGroups']);
$event->setParameter('cookieGroups', $cookieGroups);
}
}
/**
* Removes disabled cookies from group
*
* @param string $salesChannelId
* @param array $cookieGroups
* @return array
*/
private function filterIframeCookie(string $salesChannelId, array $cookieGroups): array
{
$config = $this->systemConfigService->get('BpaPlatformVideoIframeCookieHandler.config', $salesChannelId);
foreach ($cookieGroups as $groupIndex => $cookieGroup) {
if ($cookieGroup['snippet_name'] !== 'cookie.groupStatistical') {
continue;
}
foreach (BpaPlatformVideoIframeCookieHandler::AVAILABLE_IFRAMES as $iframe) {
foreach ($cookieGroup['entries'] as $entryIdx => $entry) {
if ($entry['cookie'] !== $iframe['cookieName']) {
continue;
}
if (!$config[$iframe['configName']]) {
unset($cookieGroups[$groupIndex]['entries'][$entryIdx]);
}
}
}
if (\count($cookieGroups[$groupIndex]['entries']) === 0) {
unset($cookieGroups[$groupIndex]);
}
}
return $cookieGroups;
}
}