1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Psr7Middlewares\Middleware; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
7
|
|
|
use Psr7Middlewares\Utils; |
8
|
|
|
|
9
|
|
|
class GoogleAnalytics |
10
|
|
|
{ |
11
|
|
|
use Utils\HtmlInjectorTrait; |
12
|
|
|
use Utils\AttributeTrait; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @var string The site's ID |
16
|
|
|
*/ |
17
|
|
|
private $siteId; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Constructor. Set the site's ID. |
21
|
|
|
* |
22
|
|
|
* @param string $siteId |
23
|
|
|
*/ |
24
|
|
|
public function __construct($siteId) |
25
|
|
|
{ |
26
|
|
|
$this->siteId = (string) $siteId; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Execute the middleware. |
31
|
|
|
* |
32
|
|
|
* @param ServerRequestInterface $request |
33
|
|
|
* @param ResponseInterface $response |
34
|
|
|
* @param callable $next |
35
|
|
|
* |
36
|
|
|
* @return ResponseInterface |
37
|
|
|
*/ |
38
|
|
View Code Duplication |
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) |
39
|
|
|
{ |
40
|
|
|
$response = $next($request, $response); |
41
|
|
|
|
42
|
|
|
if (Utils\Helpers::getMimeType($response) === 'text/html' && !Utils\Helpers::isAjax($request)) { |
43
|
|
|
return $this->inject($response, $this->getCode()); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
return $response; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* Returns the google code. |
51
|
|
|
* https://github.com/h5bp/html5-boilerplate/blob/master/src/index.html. |
52
|
|
|
* |
53
|
|
|
* @return string |
54
|
|
|
*/ |
55
|
|
|
private function getCode() |
56
|
|
|
{ |
57
|
|
|
return <<<GA |
58
|
|
|
<script> |
59
|
|
|
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]= |
60
|
|
|
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date; |
61
|
|
|
e=o.createElement(i);r=o.getElementsByTagName(i)[0]; |
62
|
|
|
e.src='https://www.google-analytics.com/analytics.js'; |
63
|
|
|
r.parentNode.insertBefore(e,r)}(window,document,'script','ga')); |
64
|
|
|
ga('create','{$this->siteId}','auto');ga('send','pageview'); |
65
|
|
|
</script> |
66
|
|
|
GA; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|