Completed
Push — master ( 069b3e...031a7a )
by Paweł
09:08
created

ArticleEventsExtension   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 154
Duplicated Lines 3.9 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 4
dl 6
loc 154
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getFunctions() 0 7 1
B renderLinkImpressionCount() 3 94 2
A renderPageViewCount() 3 28 4

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
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Core Bundle.
7
 *
8
 * Copyright 2017 Sourcefabric z.u. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2017 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\CoreBundle\Twig;
18
19
use SWP\Bundle\CoreBundle\Model\ArticleInterface;
20
use SWP\Component\TemplatesSystem\Gimme\Meta\Meta;
21
use Twig\Extension\AbstractExtension;
22
use Twig\TwigFunction;
23
24
class ArticleEventsExtension extends AbstractExtension
25
{
26
    protected $analyticsHost;
27
28
    public function __construct(string $analyticsHost = null)
29
    {
30
        $this->analyticsHost = $analyticsHost;
31
    }
32
33
    /**
34
     * @return TwigFunction[]
35
     */
36
    public function getFunctions()
37
    {
38
        return [
39
            new TwigFunction('countPageView', [$this, 'renderPageViewCount'], ['is_safe' => ['html']]),
40
            new TwigFunction('countArticlesImpressions', [$this, 'renderLinkImpressionCount'], ['is_safe' => ['html']]),
41
        ];
42
    }
43
44
    /**
45
     * @param Meta $meta
0 ignored issues
show
Bug introduced by
There is no parameter named $meta. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
46
     *
47
     * @return string|void
48
     */
49
    public function renderLinkImpressionCount()
50
    {
51
        $jsTemplate = <<<'EOT'
52
<script type="text/javascript" async>
53
window.addEventListener('load',function(){
54
function isInCurrentViewport(el) {
55
    const rect = el.getBoundingClientRect();
56
57
    return (
58
        rect.top >= 0 &&
59
        rect.left >= 0 &&
60
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
61
        rect.right <= (window.innerWidth || document.documentElement.clientWidth)
62
    );
63
}
64
65
66
let arr = [], links = [], processedLinks = [], l = document.links;
67
const hostname = window.location.hostname;
68
var iterator = 0;
69
var breakpoint = 200;
70
71
var process = function process() {
72
  links = [];
73
  arr = [];
74
  // filter out section pages
75
  for(let i=0; i<l.length; i++) {
76
      const parts = l[i].pathname.split('/');
77
      if (parts.length > 2 && isInCurrentViewport(l[i]) && processedLinks.indexOf(l[i].href) === -1) {
78
          links.push(l[i]);
79
      }
80
  }
81
  // filter out links with data-article, add article id
82
  for(let i=0; i<links.length; i++) {
83
      const attr = links[i].dataset['article'];
84
      // if attribute not in array
85
      if(typeof attr !== 'undefined' && arr.indexOf(attr) === -1 && isInCurrentViewport(links[i]) && processedLinks.indexOf(links[i].href) === -1){
86
          arr.push(attr); 
87
          links.splice(i, 1);
88
      }
89
  }
90
  
91
  // filter out links different than current domain
92
  for(let i=0; i<links.length; i++){
93
      if(arr.indexOf(links[i].href) === -1 && links[i].href.indexOf(hostname) !== -1){
94
          arr.push(links[i].href);
95
      }
96
  }
97
98
  processedLinks = unique(processedLinks.concat(arr));
99
  
100
  if (arr.length > 0) {
101
      let xhr = new XMLHttpRequest();
102
      let read_date = new Date();
103
      let request_randomizer = "&" + read_date.getTime() + Math.random();
104
      xhr.open('POST', '/_swp_analytics?type=impression'+request_randomizer);
105
      xhr.setRequestHeader("Content-Type", "application/json");
106
      xhr.send(JSON.stringify(arr));
107
  }
108
}
109
110
var countImpressions = function countImpressions() {
111
    let scrollDown = document.body.scrollTop || document.documentElement.scrollTop;
112
    if (scrollDown >= breakpoint) {
113
       process();
114
       breakpoint += 200;
115
       iterator++;
116
    }
117
}
118
119
var unique = function unique(array) {
120
    let a = array.concat();
121
    for(let i=0; i<a.length; ++i) {
122
        for(let j=i+1; j<a.length; ++j) {
123
            if(a[i] === a[j])
124
                a.splice(j--, 1);
125
        }
126
    }
127
128
    return a;
129
}
130
131
window.onscroll = function() {countImpressions()};
132
process();
133
})
134
</script>
135
EOT;
136
137 View Code Duplication
        if (null !== $this->analyticsHost) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
138
            $jsTemplate = str_replace('/_swp_analytics', $this->analyticsHost.'/_swp_analytics', $jsTemplate);
139
        }
140
141
        return $jsTemplate;
142
    }
143
144
    /**
145
     * @param Meta $meta
146
     *
147
     * @return string|void
148
     */
149
    public function renderPageViewCount(Meta $meta = null)
150
    {
151
        if (null === $meta) {
152
            return;
153
        }
154
155
        $jsTemplate = <<<'EOT'
156
<script type="text/javascript" async>
157
window.addEventListener('load',function(){
158
var xhr = new XMLHttpRequest();
159
var read_date = new Date();
160
var request_randomizer = "&" + read_date.getTime() + Math.random();
161
xhr.open('GET', '/_swp_analytics?articleId=%s'+request_randomizer+'&ref='+document.referrer);
162
xhr.send();
163
})
164
</script>
165
EOT;
166
        $article = $meta->getValues();
167
        if (!$article instanceof ArticleInterface) {
168
            return;
169
        }
170
171 View Code Duplication
        if (null !== $this->analyticsHost) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
172
            $jsTemplate = str_replace('/_swp_analytics', $this->analyticsHost.'/_swp_analytics', $jsTemplate);
173
        }
174
175
        return sprintf($jsTemplate, $article->getId());
176
    }
177
}
178