Created
January 15, 2019 13:01
-
-
Save Langmans/bdfeade7eae740b6e9492b2ba71a874b to your computer and use it in GitHub Desktop.
google analytics provider (gtag) for silex 1.x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace DMG\ServiceProvider; | |
use Silex\Application; | |
use Silex\ServiceProviderInterface; | |
use Symfony\Component\HttpFoundation\Request; | |
use Symfony\Component\HttpFoundation\Response; | |
/** | |
* Class GoogleAnalyticsProvider | |
* | |
* @package DMG\ServiceProvider | |
*/ | |
class GoogleAnalyticsProvider implements ServiceProviderInterface | |
{ | |
/** @var string */ | |
protected $ua; | |
public function __construct($ua) | |
{ | |
$this->ua = $ua; | |
} | |
/** | |
* @param \Silex\Application $app | |
*/ | |
public function boot(Application $app) | |
{ | |
$app->after(array($this, 'inject')); | |
} | |
/** | |
* @param \Silex\Application $app | |
*/ | |
public function register(Application $app) | |
{ | |
} | |
public function inject(Request $request, Response $response) | |
{ | |
if ($response->getStatusCode() == 200 && | |
false === strpos($request->get('_route'), 'cms.') && | |
false !== stripos($response->headers->get('Content-Type'), 'html') && | |
false !== stripos($content = $response->getContent(), '</head>') | |
) { | |
$method = __METHOD__; | |
$ua = $this->ua; | |
$ua_encoded = json_encode($this->ua); | |
$response->setContent(preg_replace('@<head(\s[^>]+)?>@i', | |
'${0}'."\n\t<!-- Global site tag (gtag.js) - Google Analytics --> | |
<script async src=\"https://www.googletagmanager.com/gtag/js?id=$ua\"></script> | |
<script> | |
window.dataLayer = window.dataLayer || []; | |
function gtag(){dataLayer.push(arguments);} | |
gtag('js', new Date()); | |
gtag('config', $ua_encoded); | |
</script>\n", | |
$content)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment