View source
<?php
namespace Drupal\multidomain_google_analytics\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\domain\DomainNegotiatorInterface;
class GoogleAnalyticResponseSubscriber implements EventSubscriberInterface {
protected $config;
protected $activeDomain;
public function __construct(ConfigFactoryInterface $configFactory, DomainNegotiatorInterface $negotiator) {
$this->config = $configFactory
->get('multidomain_google_analytics.settings');
if ($negotiator
->getActiveDomain()) {
$this->activeDomain = $negotiator
->getActiveId();
}
}
public function addTag(FilterResponseEvent $event) {
if (!$event
->isMasterRequest()) {
return;
}
$response = $event
->getResponse();
$compact = '';
if ($this->activeDomain) {
$compact = $this->config
->get($this->activeDomain);
}
if ($compact) {
$response_text = preg_replace('@<body[^>]*>@', '$0' . $this
->getTag($compact), $response
->getContent(), 1);
if ($response_text) {
$response
->setContent($response_text);
}
}
}
public function getTag($compact = FALSE) {
$script = [];
$script = <<<EOS
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '{<span class="php-variable">$compact</span>}', 'auto');
ga('require', 'displayfeatures');
ga('send', 'pageview');
</script>
EOS;
if ($compact) {
$script = str_replace([
"\n",
' ',
], '', $script);
}
$script = <<<EOS
<!-- Google Analytics -->
{<span class="php-variable">$script</span>}
<!-- End Google Analytics -->
EOS;
return $script;
}
public static function getSubscribedEvents() {
$events[KernelEvents::RESPONSE][] = [
'addTag',
-500,
];
return $events;
}
}