vendor/pimcore/pimcore/bundles/CoreBundle/EventListener/Frontend/GoogleAnalyticsCodeListener.php line 45

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4.  * Pimcore
  5.  *
  6.  * This source file is available under two different licenses:
  7.  * - GNU General Public License version 3 (GPLv3)
  8.  * - Pimcore Commercial License (PCL)
  9.  * Full copyright and license information is available in
  10.  * LICENSE.md which is distributed with this source code.
  11.  *
  12.  *  @copyright  Copyright (c) Pimcore GmbH (http://www.pimcore.org)
  13.  *  @license    http://www.pimcore.org/license     GPLv3 and PCL
  14.  */
  15. namespace Pimcore\Bundle\CoreBundle\EventListener\Frontend;
  16. use Pimcore\Analytics\Google\Tracker;
  17. use Pimcore\Bundle\CoreBundle\EventListener\Traits\EnabledTrait;
  18. use Pimcore\Bundle\CoreBundle\EventListener\Traits\PimcoreContextAwareTrait;
  19. use Pimcore\Bundle\CoreBundle\EventListener\Traits\PreviewRequestTrait;
  20. use Pimcore\Bundle\CoreBundle\EventListener\Traits\ResponseInjectionTrait;
  21. use Pimcore\Bundle\CoreBundle\EventListener\Traits\StaticPageContextAwareTrait;
  22. use Pimcore\Http\Request\Resolver\PimcoreContextResolver;
  23. use Pimcore\Tool;
  24. use Symfony\Component\HttpKernel\Event\ResponseEvent;
  25. /**
  26.  * @internal
  27.  */
  28. class GoogleAnalyticsCodeListener
  29. {
  30.     use EnabledTrait;
  31.     use ResponseInjectionTrait;
  32.     use PimcoreContextAwareTrait;
  33.     use PreviewRequestTrait;
  34.     use StaticPageContextAwareTrait;
  35.     public function __construct(private Tracker $tracker)
  36.     {
  37.     }
  38.     public function onKernelResponse(ResponseEvent $event)
  39.     {
  40.         if (!$this->isEnabled()) {
  41.             return;
  42.         }
  43.         $request $event->getRequest();
  44.         if (!$event->isMainRequest() && !$this->matchesStaticPageContext($request)) {
  45.             return;
  46.         }
  47.         // only inject analytics code on non-admin requests
  48.         // and check for static page context for CLI generation
  49.         if (!$this->matchesPimcoreContext($requestPimcoreContextResolver::CONTEXT_DEFAULT)
  50.             && !$this->matchesStaticPageContext($request)) {
  51.             return;
  52.         }
  53.         if (!Tool::useFrontendOutputFilters()) {
  54.             return;
  55.         }
  56.         if ($this->isPreviewRequest($request)) {
  57.             return;
  58.         }
  59.         $response $event->getResponse();
  60.         if (!$this->isHtmlResponse($response)) {
  61.             return;
  62.         }
  63.         $code $this->tracker->generateCode();
  64.         if (empty($code)) {
  65.             return;
  66.         }
  67.         $this->injectBeforeHeadEnd($response$code);
  68.     }
  69. }