Completed
Pull Request — master (#6)
by methylbro
02:32
created

TagcommanderExtension::getFunctions()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 7
Bugs 1 Features 0
Metric Value
c 7
b 1
f 0
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
cc 2
eloc 5
nc 2
nop 0
crap 2
1
<?php
2
3
/**
4
* This file is part of the Meup TagCommander Bundle.
5
*
6
* (c) 1001pharmacies <http://github.com/1001pharmacies/tagcommander-bundle>
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 Meup\Bundle\TagcommanderBundle\Twig;
13
14
use Meup\Bundle\TagcommanderBundle\EventDispatcher\Event\DeployContainer;
15
use Meup\Bundle\TagcommanderBundle\EventDispatcher\Event\Track;
16
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
17
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
18
use Symfony\Component\Serializer\Encoder\JsonEncoder;
19
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
20
use Symfony\Component\Serializer\Serializer;
21
22
/**
23
 *
24
 */
25
class TagcommanderExtension extends \Twig_Extension
26
{
27
    /**
28
     * @var ParameterBagInterface
29
     */
30
    protected $datalayer;
31
32
    /**
33
     * @var EventDispatcherInterface
34
     */
35
    protected $dispatcher;
36
37
    /**
38
     * @var string
39
     */
40
    protected $tcVars;
41
42
    /**
43
     * @var array
44
     */
45
    protected $events = array();
46
47
    /**
48
     * @var array
49
     */
50
    protected $containers = array();
51
52
    /**
53
     * @var string
54
     */
55
    protected $defaultEvent = null;
56
57
    /**
58
     * @var Serializer
59
     */
60
    protected $serializer;
61
62
    /**
63
     * @var array
64
     */
65
    static protected $twigFunctions = array(
66
        'tc_vars'      => 'tcVars',
67
        'tc_container' => 'tcContainer',
68
        'tc_event'     => 'tcEvent',
69
    );
70
71
    /**
72
     * @param ParameterBagInterface $datalayer
73
     * @param EventDispatcherInterface $dispatcher
74
     * @param string $tcVars
75
     */
76 1
    public function __construct(
77
        ParameterBagInterface $datalayer,
78
        EventDispatcherInterface $dispatcher,
79
        $tcVars = 'tc_vars'
80
    ) {
81 1
        $this->datalayer     = $datalayer;
82 1
        $this->dispatcher    = $dispatcher;
83 1
        $this->tcVars        = $tcVars;
84 1
        $this->serializer    = new Serializer(
85 1
            array(new ObjectNormalizer()),
86 1
            array(new JsonEncoder())
87 1
        );
88 1
    }
89
90
    /**
91
     * @return string|boolean|integer|double|null
92
     */
93 1
    protected function serializeWithValues($values = array())
94
    {
95 1
        $datalayer = clone $this->datalayer;
96
97 1
        return $this
98
            ->serializer
99 1
            ->serialize(
100 1
                array_merge(
101 1
                    $datalayer->all(),
102
                    $values
103 1
                ),
104
                'json'
105 1
            )
106 1
        ;
107
    }
108
109
    /** 
110
     * @param Array $values
111
     * @return string
112
     */
113 1
    public function tcVars($values = array())
114
    {
115 1
        return sprintf(
116 1
            '<script type="text/javascript">var %s = %s;</script>',
117 1
            $this->tcVars,
118 1
            $this->serializeWithValues($values)
119 1
        );
120
    }
121
122
    /** 
123
     * @param array $event
124
     * @param boolean $setAsDefault
125
     * @return self
126
     */
127 1
    public function addEvent($event, $setAsDefault = false)
128
    {
129 1
        $this->events[$event['name']] = $event;
130
131 1
        if ($setAsDefault || (!$setAsDefault && !$this->defaultEvent)) {
132 1
            $this->defaultEvent = $event['name'];
133 1
        }
134
135 1
        return $this;
136
    }
137
138
    /**
139
     * @param string $eventName
140
     * @param array $values 
141
     * @param string|null $tracker
142
     * @return string
143
     */
144 1
    public function tcEvent($eventName, $values = array(), $tracker = null)
145
    {
146 1
        if (is_null($tracker)) {
147 1
            $tracker = $this->defaultEvent;
148 1
        }
149
150 1
        $function = $this->events[$tracker]['function'];
151
152 1
        $event = new Track($tracker, $eventName, array_merge($this->datalayer->all(), $values));
153 1
        $this->dispatcher->dispatch('tc_event', $event);
154
155 1
        return sprintf(
156 1
            "%s('%s', %s);",
157 1
            $function,
158 1
            $eventName,
159 1
            $this->serializeWithValues($values)
160 1
        );
161
    }
162
163
    /**
164
     * @param array $container
165
     * @return self
166
     */
167 1
    public function addContainer($container)
168
    {
169 1
        $this->containers[$container['name']] = $container;
170
171 1
        return $this;
172
    }
173
174 1
    private function containerHas($container, $parameterName)
175
    {
176 1
        return array_key_exists($parameterName, $container) && !empty($container[$parameterName]);
177
    }
178
179 1 View Code Duplication
    private function containerSrc($containerName)
1 ignored issue
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...
180
    {
181 1
        $container = $this->containers[$containerName];
182 1
        $src       = $container['script'];
183 1
        if ($this->containerHas($container, 'version')) {
184 1
            $src .= sprintf('?%s', $container['version']);
185 1
        }
186 1
        return sprintf('<script type="text/javascript" src="%s"></script>', $src);
187
    }
188
189 1 View Code Duplication
    private function containerAlternative($containerName)
1 ignored issue
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...
190
    {
191 1
        $container = $this->containers[$containerName];
192 1
        $result    = '';
193 1
        if ($this->containerHas($container, 'alternative')) {
194 1
            $result .= sprintf(
195 1
                '<noscript><iframe src="%s" width="1" height="1" rel="noindex,nofollow"></iframe></noscript>',
196 1
                $container['alternative']
197 1
            );
198 1
        }
199 1
        return $result;
200
    }
201
202
    /**
203
     * @param string $containerName
204
     * @return string
205
     */
206 1
    public function tcContainer($containerName)
207
    {
208 1
        $container = $this->containers[$containerName];
209
210 1
        $this
211
            ->dispatcher
212 1
            ->dispatch(
213 1
                'tc_container',
214 1
                new DeployContainer(
215 1
                    $containerName,
216 1
                    $container['script'],
217 1
                    $container['version'],
218 1
                    $container['alternative']
219 1
                )
220 1
            )
221
        ;
222
223 1
        return $this->containerSrc($containerName).$this->containerAlternative($containerName);
224
    }
225
226
    /**
227
     * @param string $twigName
228
     * @param string $methodName
229
     * @return \Twig_SimpleFunction
230
     */
231 1
    private function makeFunction($twigName, $methodName)
232
    {
233 1
        return new \Twig_SimpleFunction(
234 1
            $twigName,
235 1
            array($this, $methodName),
236
            array(
237 1
                'is_safe' => array('html'),
238
            )
239 1
        );
240
    }
241
242
    /**
243
     * @return \Twig_SimpleFunction[]
244
     */
245 1
    public function getFunctions()
246
    {
247 1
        $result = array();
248 1
        foreach (self::$twigFunctions as $twigName => $methodName) {
249 1
            $result[] = $this->makeFunction($twigName, $methodName);
250 1
        }
251 1
        return $result;
252
    }
253
254
    /**
255
     * @return string
256
     */
257 1
    public function getName()
258
    {
259 1
        return 'tagcommander_extension';
260
    }
261
}
262