<?php
declare(strict_types = 1);
namespace Aufwind\CookiebotBundle\EventSubscriber;
use Aufwind\CookiebotBundle\CookiebotService;
use Aufwind\CookiebotBundle\Service\ConfigManager;
use Pimcore\Analytics\SiteId\SiteIdProvider;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\EnabledTrait;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\PimcoreContextAwareTrait;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\PreviewRequestTrait;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\ResponseInjectionTrait;
use Pimcore\Http\Request\Resolver\PimcoreContextResolver;
use Pimcore\Tool;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Templating\EngineInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
class CookiebotInsertSubscriber implements EventSubscriberInterface
{
use EnabledTrait;
use ResponseInjectionTrait;
use PimcoreContextAwareTrait;
use PreviewRequestTrait;
public function __construct(
// protected SiteIdProvider $siteIdProvider,
// protected EventDispatcherInterface $eventDispatcher,
// protected EngineInterface $templatingEngine,
protected ConfigManager $configManager,
protected CookiebotService $cookiebotService,
) {
}
public function onKernelResponse(ResponseEvent $event): void
{
if (!$this->configManager->isAutoInsert()) {
return;
}
if (!$this->isEnabled()) {
return;
}
$request = $event->getRequest();
if (!$event->isMainRequest()) {
return;
}
// only inject tag manager code on non-admin requests
if (!$this->matchesPimcoreContext($request, PimcoreContextResolver::CONTEXT_DEFAULT)) {
return;
}
if (!Tool::useFrontendOutputFilters()) {
return;
}
if ($this->isPreviewRequest($request)) {
return;
}
// $siteId = $this->siteIdProvider->getForRequest($event->getRequest());
// $siteKey = $siteId->getConfigKey();
$response = $event->getResponse();
if (!$this->isHtmlResponse($response)) {
return;
}
if (!$this->cookiebotService->isCookieBotEnabled()) {
return;
}
$content = $response->getContent();
$scriptTag = $this->cookiebotService->getScriptCode();
$searchString = '<script';
$replace = '';
if (!empty($scriptTag)) {
// search for the end <head> tag, and insert the google tag manager code before
// this method is much faster than using simple_html_dom and uses less memory
$position = stripos($content, $searchString);
if (false === $position) {
$searchString = '<meta charset="utf-8">';
// $append = $searchString;
// $prepend = '';
$position = stripos($content, $searchString);
$replace = $searchString . $scriptTag;
} else {
$replace = $scriptTag . $searchString;
}
if (false !== $position) {
$content = substr_replace($content, $replace, $position, strlen($searchString));
}
}
$response->setContent($content);
}
public static function getSubscribedEvents()
{
return [
// KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::RESPONSE => [
['onKernelResponse', -108],
],
];
}
}