Completed
Pull Request — 5.6 (#2830)
by Jeroen
14:14
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 [
39
            new TwigFunction(
40
                'google_analytics_initialize',
41
                [$this, 'renderInitialize'],
42
                ['is_safe' => ['html'], 'needs_environment' => true]
43
            ),
44
            new TwigFunction(
45
                'google_analytics_track_order',
46
                [$this, 'renderECommerceTracking'],
47
                ['is_safe' => ['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 array|null $options Example: {account_id: 'UA-XXXXX-Y'}
82
     *
83
     * @return string the HTML rendered
84
     *
85
     * @throws Error when the Google Analytics ID is nowhere to be found
86
     */
87
    public function renderInitialize(Environment $environment, $options = null)
88
    {
89
        if (\is_null($options)) {
90
            $options = [];
91
        }
92
93
        $defaults = [];
94
95
        $this->setOptionIfNotSet($defaults, $this->accountVarName, $this->accountId);
96
97
        // Things set in $options will override things set in $defaults.
98
        $options = array_merge($defaults, $options);
99
100
        if (!$this->isOptionSet($options, $this->accountVarName)) {
101
            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'.");
102
        }
103
104
        $template = $environment->load('@KunstmaanSeo/GoogleAnalyticsTwigExtension/init.html.twig');
105
106
        return $template->render($options);
107
    }
108
109
    /**
110
     * @return string the HTML rendered
111
     */
112
    public function renderECommerceTracking(Environment $environment, Order $order)
113
    {
114
        $order = $this->orderPreparer->prepare($order);
115
        $options = $this->orderConverter->convert($order);
116
        $template = $environment->load(
117
            '@KunstmaanSeo/GoogleAnalyticsTwigExtension/ecommerce_tracking.html.twig'
118
        );
119
120
        return $template->render($options);
121
    }
122
123
    /**
124
     * Prefer the given option if already set. Otherwise set the value given.
125
     *
126
     * @param array  &$arr   This is modified in place
127
     * @param string $option the key in the $arr array
128
     * @param mixed  $value  the new value if the option wasn't set already
129
     */
130
    private function setOptionIfNotSet(&$arr, $option, $value)
131
    {
132
        if ($this->isOptionSet($arr, $option)) {
133
            $arr[$option] = $value;
134
        }
135
    }
136
137
    /**
138
     * Check if an option is set.
139
     *
140
     * @param array  $arr    the array to check
141
     * @param string $option the key in the $arr array
142
     *
143
     * @return bool
144
     */
145
    private function isOptionSet($arr, $option)
146
    {
147
        return !isset($arr[$option]) || !empty($arr[$option]);
148
    }
149
}
150