Skip to content

Commit

Permalink
Merge pull request #12525 from martoboto/analytics-to-gtag-v4
Browse files Browse the repository at this point in the history
Update analytics.js to gtag to support ga4
  • Loading branch information
escopecz committed Jul 18, 2023
2 parents 5c4a0ff + bb4e234 commit 221f00d
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 21 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

declare(strict_types=1);

namespace Mautic\CoreBundle\Tests\Functional\Controller;

use Mautic\CoreBundle\Test\MauticMysqlTestCase;
use PHPUnit\Framework\Assert;
use Symfony\Component\HttpFoundation\Response;

/**
* This test is breaking other tests, so running it in a separate process.
*
* @runTestsInSeparateProcesses
*
* @preserveGlobalState disabled
*/
final class JsControllerTest extends MauticMysqlTestCase
{
protected function setUp(): void
{
$this->configParams['google_analytics_id'] = 'G-F3825DS9CD';
$this->configParams['google_analytics_trackingpage_enabled'] = true;
$this->configParams['site_url'] = 'https://mautic.test';
$this->configParams['google_analytics_anonymize_ip'] = 'testIndexActionRendersSuccessfullyWithAnonymizeIp' === $this->getName();
parent::setUp();
}

public function testIndexActionRendersSuccessfully(): void
{
$this->client->request('GET', '/mtc.js');
Assert::assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
Assert::assertStringContainsString('https://www.googletagmanager.com/gtag/js?id=G-F3825DS9CD', $this->client->getResponse()->getContent());
Assert::assertStringContainsString('gtag(\'config\',\'G-F3825DS9CD\')', $this->client->getResponse()->getContent());
}

public function testIndexActionRendersSuccessfullyWithAnonymizeIp(): void
{
$this->client->request('GET', '/mtc.js');
Assert::assertSame(Response::HTTP_OK, $this->client->getResponse()->getStatusCode());
Assert::assertStringContainsString('https://www.googletagmanager.com/gtag/js?id=G-F3825DS9CD', $this->client->getResponse()->getContent());
Assert::assertStringContainsString('gtag(\'config\',\'G-F3825DS9CD\',{"anonymize_ip":true})', $this->client->getResponse()->getContent());
}
}
51 changes: 31 additions & 20 deletions app/bundles/PageBundle/EventListener/BuildJsSubscriber.php
Original file line number Diff line number Diff line change
Expand Up @@ -495,19 +495,31 @@ public function onBuildJsForTrackingEvent(BuildJsEvent $event)
$lead = $this->trackingHelper->getLead();

if ($id = $this->trackingHelper->displayInitCode('google_analytics')) {
$gaUserId = ($lead && $lead->getId()) ? 'ga(\'set\', \'userId\', '.$lead->getId().');' : '';
$gaAnonymizeIp = $this->trackingHelper->getAnonymizeIp() ? 'ga(\'set\', \'anonymizeIp\', true);' : '';
$gtagSettings = [];

if ($this->trackingHelper->getAnonymizeIp()) {
$gtagSettings['anonymize_ip'] = true;
}

if ($lead && $lead->getId()) {
$gtagSettings['user_id'] = $lead->getId();
}

if (count($gtagSettings) > 0) {
$gtagSettings = ', '.json_encode($gtagSettings);
} else {
$gtagSettings = '';
}

$js .= <<<JS
dataLayer = window.dataLayer ? window.dataLayer : [];
(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','https://www.google-analytics.com/analytics.js','ga');
ga('create', '{$id}', 'auto');
{$gaAnonymizeIp}
{$gaUserId}
ga('send', 'pageview');
a = document.createElement('script');
a.async = 1;
a.src = 'https://www.googletagmanager.com/gtag/js?id={$id}';
document.getElementsByTagName('head')[0].appendChild(a);
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '{$id}'{$gtagSettings});
JS;
}

Expand Down Expand Up @@ -566,15 +578,14 @@ public function onBuildJsForTrackingEvent(BuildJsEvent $event)
if (typeof ga !== 'undefined' && typeof events.google_analytics !== 'undefined') {
var e = events.google_analytics;
for(var i = 0; i < e.length; i++) {
if(typeof e[i]['action'] !== 'undefined' && typeof e[i]['label'] !== 'undefined' )
ga('send', {
hitType: 'event',
eventCategory: e[i]['category'],
eventAction: e[i]['action'],
eventLabel: e[i]['label'],
});
}
for(var i = 0; i < e.length; i++) {
if(typeof e[i]['action'] !== 'undefined' && typeof e[i]['label'] !== 'undefined' ) {
gtag('event', e[i]['action'], {
'event_category': e[i]['category'],
'event_label': e[i]['label']
});
}
}
}
if (typeof events.focus_item !== 'undefined') {
Expand Down
2 changes: 1 addition & 1 deletion app/bundles/PageBundle/Helper/TrackingHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public function getAnonymizeIp()
protected function isLandingPage()
{
$server = $this->requestStack->getCurrentRequest()->server;
if (false === strpos($server->get('HTTP_REFERER'), $this->coreParametersHelper->get('site_url'))) {
if (false === strpos((string) $server->get('HTTP_REFERER'), $this->coreParametersHelper->get('site_url'))) {
return false;
}

Expand Down

0 comments on commit 221f00d

Please sign in to comment.