<?php
declare(strict_types=1);
namespace App\Component\Analytics\Helper;
use App\Entity\GoogleTagManager;
use App\Repository\GoogleTagManagerRepository;
use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Security\Http\FirewallMapInterface;
final class AdminRequestChecksExistingScriptsSubscriber implements EventSubscriberInterface
{
private const MESSAGE = 'Looks like there are Google tag manager scripts set, these won\'t work anymore. Please delete these and configure the Google tag manager id in the Google settings';
public function __construct(
private readonly FirewallMapInterface $firewallMap,
private readonly GoogleTagManagerRepository $repository,
private readonly SessionInterface $session
) {
}
public static function getSubscribedEvents(): array
{
return [
'kernel.response' => 'onResponse',
];
}
public function onResponse(ResponseEvent $event): void
{
if (
!$event->isMainRequest()
|| !$this->session instanceof Session
|| (
$this->firewallMap instanceof FirewallMap
&& 'admin' !== $this->firewallMap->getFirewallConfig($event->getRequest())?->getName()
)
) {
return;
}
$gtmScripts = array_filter(
$this->repository->getAllScripts(),
function (GoogleTagManager $script) {
return GtmScriptDetector::isGtmScript($script->getScript() ?? '');
}
);
if ([] === $gtmScripts) {
return;
}
if (\in_array(self::MESSAGE, $this->session->getFlashBag()->get('warning'), true)) {
return;
}
$this->session
->getFlashBag()
->add(
'warning',
self::MESSAGE
);
}
}