GoogleAnalytics   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 60
Duplicated Lines 16.67 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 10
loc 60
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getCode() 0 13 1
A __invoke() 10 10 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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