src/Component/Analytics/Helper/AdminRequestChecksExistingScriptsSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Component\Analytics\Helper;
  4. use App\Entity\GoogleTagManager;
  5. use App\Repository\GoogleTagManagerRepository;
  6. use Symfony\Bundle\SecurityBundle\Security\FirewallMap;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\HttpFoundation\Session\Session;
  9. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  10. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  11. use Symfony\Component\Security\Http\FirewallMapInterface;
  12. final class AdminRequestChecksExistingScriptsSubscriber implements EventSubscriberInterface
  13. {
  14.     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';
  15.     public function __construct(
  16.         private readonly FirewallMapInterface $firewallMap,
  17.         private readonly GoogleTagManagerRepository $repository,
  18.         private readonly SessionInterface $session
  19.     ) {
  20.     }
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [
  24.             'kernel.response' => 'onResponse',
  25.         ];
  26.     }
  27.     public function onResponse(ResponseEvent $event): void
  28.     {
  29.         if (
  30.             !$event->isMainRequest()
  31.             || !$this->session instanceof Session
  32.             || (
  33.                 $this->firewallMap instanceof FirewallMap
  34.                 && 'admin' !== $this->firewallMap->getFirewallConfig($event->getRequest())?->getName()
  35.             )
  36.         ) {
  37.             return;
  38.         }
  39.         $gtmScripts array_filter(
  40.             $this->repository->getAllScripts(),
  41.             function (GoogleTagManager $script) {
  42.                 return GtmScriptDetector::isGtmScript($script->getScript() ?? '');
  43.             }
  44.         );
  45.         if ([] === $gtmScripts) {
  46.             return;
  47.         }
  48.         if (\in_array(self::MESSAGE$this->session->getFlashBag()->get('warning'), true)) {
  49.             return;
  50.         }
  51.         $this->session
  52.             ->getFlashBag()
  53.             ->add(
  54.                 'warning',
  55.                 self::MESSAGE
  56.             );
  57.     }
  58. }