TagManagerTwig::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the WPFoundation library.
5
 *
6
 * Copyright (c) 2015-present LIN3S <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace LIN3S\WPFoundation\Twig;
13
14
/**
15
 * Twig function to use in Twig templates that add TagManager container adding the following code.
16
 *
17
 *     {{ tagManager('GTM-XXXXXX') }}
18
 *
19
 * Remember to call the constructor into theme before using it.
20
 *
21
 * @author Beñat Espiña <[email protected]>
22
 * @author Gorka Laucirica <[email protected]>
23
 */
24
class TagManagerTwig
25
{
26
    /**
27
     * Constructor.
28
     */
29
    public function __construct()
30
    {
31
        add_action('twig_apply_filters', function (\Twig_Environment $twig) {
0 ignored issues
show
Unused Code introduced by
The call to the function add_action() seems unnecessary as the function has no side-effects.
Loading history...
32
            $twig->addFunction(new \Twig_SimpleFunction('tagManager', [$this, 'tagManagerFunction']));
33
34
            return $twig;
35
        });
36
    }
37
38
    /**
39
     * Callback of "tagManager" Twig function.
40
     *
41
     * @param string $tagManagerId The tag manager id
42
     *
43
     * @return string
44
     */
45
    public function tagManagerFunction($tagManagerId)
46
    {
47
        return <<<EOT
48
<noscript><iframe src="//www.googletagmanager.com/ns.html?id=$tagManagerId"
49
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
50
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
51
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
52
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
53
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
54
})(window,document,'script','dataLayer','$tagManagerId');</script>
55
EOT;
56
    }
57
}
58