Completed
Push — master ( 00ed35...63fbb3 )
by Oscar
10:20
created

GoogleAnalytics::getCode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 13
rs 9.4286
cc 1
eloc 5
nc 1
nop 0
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr7Middlewares\Middleware;
6
use Psr\Http\Message\ServerRequestInterface;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr7Middlewares\Utils;
9
10
class GoogleAnalytics
11
{
12
    use Utils\HtmlInjectorTrait;
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)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
39
    {
40
        if (!Middleware::hasAttribute($request, FormatNegotiator::KEY)) {
41
            throw new RuntimeException('The GoogleAnalytics middleware needs FormatNegotiator executed before');
42
        }
43
44
        if (FormatNegotiator::getFormat($request) === 'html' && !Utils\Helpers::isAjax($request)) {
45
            $response = $this->inject($response, $this->getCode());
46
        }
47
48
        return $next($request, $response);
49
    }
50
51
    /**
52
     * Returns the google code.
53
     * https://github.com/h5bp/html5-boilerplate/blob/master/src/index.html.
54
     * 
55
     * @return string
56
     */
57
    private function getCode()
58
    {
59
        return <<<GA
60
<script>
61
    (function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
62
    function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
63
    e=o.createElement(i);r=o.getElementsByTagName(i)[0];
64
    e.src='https://www.google-analytics.com/analytics.js';
65
    r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
66
    ga('create','{$this->siteId}','auto');ga('send','pageview');
67
</script>
68
GA;
69
    }
70
}
71