Commit 8fa0fe5f authored by Avris's avatar Avris

Modernise to 4.0

parent c776124e
......@@ -10,7 +10,8 @@
"homepage": "https://avris.it"
}],
"require": {
"avris/micrus": "^3.0"
"avris/micrus": "^4.0",
"avris/micrus-twig": "^4.0"
},
"autoload": {
"psr-4": { "Avris\\Micrus\\GoogleAnalytics\\": "src" }
......
<?php
namespace Avris\Micrus\GoogleAnalytics;
use Avris\Dispatcher\EventSubscriberInterface;
use Avris\Micrus\Bootstrap\Terminator;
use Avris\Micrus\Controller\Http\RequestInterface;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
class GoogleAnalytics extends \Twig_Extension implements EventSubscriberInterface
final class GoogleAnalytics extends AbstractExtension
{
const CODE = <<<HTML
<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','https://www.google-analytics.com/analytics.js','ga');
ga('create', '%s', 'auto');
ga('send', 'pageview');
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '%s');
</script>
HTML;
......@@ -23,18 +22,23 @@ HTML;
/** @var string */
private $trackingId;
/** @var string[] */
/** @var array[] */
private $queue = [];
public function __construct(string $envGaTrackingId)
public function __construct(string $envGaTrackingId, Terminator $terminator)
{
$this->trackingId = $envGaTrackingId;
$terminator->attach(function () {
foreach ($this->queue as $options) {
$this->sendReport($options);
}
});
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('googleAnaytics', function () {
new TwigFunction('googleAnaytics', function () {
return $this->trackingId ? sprintf(static::CODE, $this->trackingId) : '';
}, ['is_safe' => ['html']]),
];
......@@ -84,14 +88,4 @@ HTML;
curl_exec($ch);
curl_close($ch);
}
public function getSubscribedEvents(): iterable
{
// TODO use Terminator
yield 'terminate' => function () {
foreach ($this->queue as $options) {
$this->sendReport($options);
}
};
}
}
......@@ -12,7 +12,7 @@ final class GoogleAnalyticsModule implements ModuleInterface, ParametersProvider
public function getParametersDefaults(): array
{
return [
'GA_TRACKING_ID' => 'GOOGLE_ANALYTICS_TRACKING_ID',
'GA_TRACKING_ID' => '',
];
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment