Completed
Push — master ( 06c1ce...67d37c )
by Jeroen
06:20
created

SeoBundle/Twig/GoogleAnalyticsTwigExtension.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\SeoBundle\Twig;
4
5
use Kunstmaan\SeoBundle\Helper\Order;
6
use Kunstmaan\SeoBundle\Helper\OrderConverter;
7
use Kunstmaan\SeoBundle\Helper\OrderPreparer;
8
use Twig\Environment;
9
use Twig\Error\Error;
10
use Twig\Error\RuntimeError;
11
use Twig\Extension\AbstractExtension;
12
use Twig\TwigFunction;
13
14
/**
15
 * Twig extensions for Google Analytics
16
 *
17
 * @final since 5.4
18
 */
19
class GoogleAnalyticsTwigExtension extends AbstractExtension
20
{
21
    protected $accountVarName = 'account_id';
22
23
    protected $accountId;
24
25
    /** @var OrderPreparer */
26
    protected $orderPreparer;
27
28
    /** @var OrderConverter */
29
    protected $orderConverter;
30
31
    /**
32
     * Returns a list of functions to add to the existing list.
33
     *
34
     * @return array An array of functions
0 ignored issues
show
Consider making the return type a bit more specific; maybe use TwigFunction[].

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
35
     */
36
    public function getFunctions()
37
    {
38
        return array(
39
            new TwigFunction(
40
                'google_analytics_initialize',
41
                array($this, 'renderInitialize'),
42
                array('is_safe' => array('html'), 'needs_environment' => true)
43
            ),
44
            new TwigFunction(
45
                'google_analytics_track_order',
46
                array($this, 'renderECommerceTracking'),
47
                array('is_safe' => array('html'), 'needs_environment' => true)
48
            ),
49
        );
50
    }
51
52
    /**
53
     * @param string $id the Google Analytics Account ID
54
     */
55
    public function setAccountID($id)
56
    {
57
        $this->accountId = $id;
58
    }
59
60
    /**
61
     * @param OrderPreparer $preparer
62
     */
63
    public function setOrderPreparer($preparer)
64
    {
65
        $this->orderConverter = $preparer;
0 ignored issues
show
Documentation Bug introduced by
It seems like $preparer of type object<Kunstmaan\SeoBundle\Helper\OrderPreparer> is incompatible with the declared type object<Kunstmaan\SeoBundle\Helper\OrderConverter> of property $orderConverter.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
66
    }
67
68
    /**
69
     * @param OrderConverter $converter
70
     */
71
    public function setOrderConverter($converter)
72
    {
73
        $this->orderConverter = $converter;
74
    }
75
76
    /**
77
     * Renders the default Google Analytics JavaScript.
78
     *
79
     * If the options are not set it'll try and load the account ID from your parameters (google.analytics.account_id)
80
     *
81
     * @param Environment $environment
82
     * @param array|null  $options     Example: {account_id: 'UA-XXXXX-Y'}
83
     *
84
     * @return string the HTML rendered
85
     *
86
     * @throws Error when the Google Analytics ID is nowhere to be found
87
     */
88
    public function renderInitialize(Environment $environment, $options = null)
89
    {
90
        if (\is_null($options)) {
91
            $options = array();
92
        }
93
94
        $defaults = array();
95
96
        $this->setOptionIfNotSet($defaults, $this->accountVarName, $this->accountId);
97
98
        // Things set in $options will override things set in $defaults.
99
        $options = array_merge($defaults, $options);
100
101
        if (!$this->isOptionSet($options, $this->accountVarName)) {
102
            throw new RuntimeError("The google_analytics_initialize function depends on a Google Analytics account ID. You can either pass this along in the initialize_google_analytics function ($this->accountVarName), provide a variable under 'parameters.google.analytics.account_id'.");
103
        }
104
105
        $template = $environment->load('@KunstmaanSeo/GoogleAnalyticsTwigExtension/init.html.twig');
106
107
        return $template->render($options);
108
    }
109
110
    /**
111
     * @param Environment $environment
112
     * @param Order       $order
113
     *
114
     * @return string the HTML rendered
115
     */
116
    public function renderECommerceTracking(Environment $environment, Order $order)
117
    {
118
        $order = $this->orderPreparer->prepare($order);
119
        $options = $this->orderConverter->convert($order);
120
        $template = $environment->load(
121
            '@KunstmaanSeo/GoogleAnalyticsTwigExtension/ecommerce_tracking.html.twig'
122
        );
123
124
        return $template->render($options);
125
    }
126
127
    /**
128
     * Prefer the given option if already set. Otherwise set the value given.
129
     *
130
     * @param array  &$arr   This is modified in place
131
     * @param string $option the key in the $arr array
132
     * @param mixed  $value  the new value if the option wasn't set already
133
     */
134
    private function setOptionIfNotSet(&$arr, $option, $value)
135
    {
136
        if ($this->isOptionSet($arr, $option)) {
137
            $arr[$option] = $value;
138
        }
139
    }
140
141
    /**
142
     * Check if an option is set.
143
     *
144
     * @param array  $arr    the array to check
145
     * @param string $option the key in the $arr array
146
     *
147
     * @return bool
148
     */
149
    private function isOptionSet($arr, $option)
150
    {
151
        return !isset($arr[$option]) || !empty($arr[$option]);
152
    }
153
}
154