<?php
declare(strict_types = 1);
namespace Aufwind\CookiebotBundle\EventSubscriber;
use Aufwind\WebFeatureBundle\FeatureService;
use Pimcore\Bundle\CoreBundle\EventListener\Traits\PimcoreContextAwareTrait;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class GoogleMapsSubscriber implements EventSubscriberInterface
{
use PimcoreContextAwareTrait;
public function __construct(protected FeatureService $featureService)
{
}
public function onKernelResponse(ResponseEvent $event): void
{
$response = $event->getResponse();
$context = $this->pimcoreContextResolver->getPimcoreContext($event->getRequest());
if ('admin' !== $context && HttpKernelInterface::MAIN_REQUEST === $event->getRequestType()) {
if ($this->featureService->isEnabled('google-maps')) {
$gmapsKey = \Pimcore\Model\WebsiteSetting::getByName('googleMapsKey');
if ($gmapsKey) {
$gmapsKey = $gmapsKey->getData();
}
if ($gmapsKey) {
$f = PIMCORE_WEB_ROOT . '/bundles/aufwindcookiebot/js/google-maps-cookiebot.js';
$initMap = '';
if (file_exists($f)) {
$initMap = file_get_contents($f);
}
$injectScripts = [
'google-maps-draft' => '<script defer class="google-maps google-maps-draft" src="/bundles/aufwinddraft/js/frontend/draft-googleMaps-optional.js"></script>',
'google-maps-init-google-maps' => '<script>' . $initMap . '</script>',
'google-maps-draft-google-maps-api' => '<script defer async class="google-maps google-maps-api" data-src="https://maps.googleapis.com/maps/api/js?key=' . $gmapsKey . '&callback=initGoogleMaps"></script>',
];
$script = implode('', $injectScripts);
$content = preg_replace("/(<\/head>)/", $script . '$1', $response->getContent());
$response->setContent($content);
}
}
}
}
public static function getSubscribedEvents()
{
return [
// KernelEvents::CONTROLLER => 'onKernelController',
KernelEvents::RESPONSE => 'onKernelResponse',
];
}
}