Completed
Push — master ( c3ce72...f2565d )
by Paweł
20s
created

ArticleEventsExtension   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
lcom 0
cbo 4
dl 0
loc 40
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getFunctions() 0 6 1
A renderPageViewCount() 0 22 3
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
    /**
27
     * @return TwigFunction[]
28
     */
29
    public function getFunctions()
30
    {
31
        return [
32
            new TwigFunction('countPageView', [$this, 'renderPageViewCount'], ['is_safe' => ['html']]),
33
        ];
34
    }
35
36
    /**
37
     * @param Meta $meta
38
     *
39
     * @return string|void
40
     */
41
    public function renderPageViewCount(Meta $meta = null)
42
    {
43
        if (null === $meta) {
44
            return;
45
        }
46
47
        $jsTemplate = <<<'EOT'
48
<script type="text/javascript">
49
var xhr = new XMLHttpRequest();
50
var read_date = new Date();
51
var request_randomizer = "&" + read_date.getTime() + Math.random();
52
xhr.open('GET', '/_swp_analytics?articleId=%s'+request_randomizer);
53
xhr.send();
54
</script>
55
EOT;
56
        $article = $meta->getValues();
57
        if (!$article instanceof ArticleInterface) {
58
            return;
59
        }
60
61
        return sprintf($jsTemplate, $article->getId());
62
    }
63
}
64