Completed
Push — master ( aae033...1cd9af )
by David
01:36
created

Dispatch::onWidgetsPostDispatch()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
cc 3
nc 2
nop 2
1
<?php
2
/**
3
 * Tag Manager
4
 * Copyright (c) Webmatch GmbH
5
 *
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 */
16
17
namespace WbmTagManager\Subscriber\Frontend;
18
19
use Enlight\Event\SubscriberInterface;
20
use WbmTagManager\Services\TagManagerVariables;
21
22
/**
23
 * Class Dispatch
24
 */
25
class Dispatch extends ConfigAbstract implements SubscriberInterface
26
{
27
    /**
28
     * @var TagManagerVariables
29
     */
30
    private $variables;
31
32
    /**
33
     * @var array
34
     */
35
    private $modules;
36
37
    /**
38
     * @var \Enlight_Components_Session_Namespace
39
     */
40
    private $session;
41
42
    /**
43
     * @param TagManagerVariables                   $variables
44
     * @param \Shopware_Components_Config           $config
45
     * @param array                                 $modules
46
     * @param \Enlight_Components_Session_Namespace $session
47
     */
48
    public function __construct(
49
        TagManagerVariables $variables,
50
        \Shopware_Components_Config $config,
51
        $modules,
52
        \Enlight_Components_Session_Namespace $session
53
    ) {
54
        $this->variables = $variables;
55
        $this->modules = $modules;
56
        $this->session = $session;
57
58
        parent::__construct($config);
59
    }
60
61
    /**
62
     * @return array
63
     */
64
    public static function getSubscribedEvents()
65
    {
66
        return [
67
            'Enlight_Controller_Action_PostDispatch_Frontend' => 'onPostDispatch',
68
            'Enlight_Controller_Action_PostDispatch_Widgets' => 'onWidgetsPostDispatch',
69
            'Enlight_Controller_Action_PreDispatch_Frontend' => 'onPreDispatch',
70
            'Enlight_Controller_Action_PreDispatch_Widgets' => 'onWidgetsPreDispatch',
71
        ];
72
    }
73
74
    /**
75
     * @param \Enlight_Controller_ActionEventArgs $args
76
     *
77
     * @throws \Exception
78
     */
79
    public function onPostDispatch(\Enlight_Controller_ActionEventArgs $args)
80
    {
81
        $this->handleDispatch($args);
82
    }
83
84
    /**
85
     * @param \Enlight_Controller_ActionEventArgs $args
86
     * @param bool                                $isPreDispatch
87
     *
88
     * @throws \Exception
89
     */
90
    public function onWidgetsPostDispatch(
91
        \Enlight_Controller_ActionEventArgs $args,
92
        $isPreDispatch = false
93
    ) {
94
        $module = $this->handleDispatch($args, $isPreDispatch);
95
96
        $this->variables->setModule('widgets');
97
        if ($this->variables->getVariables() && $module != 'widgets_listing_listingcount') {
98
            $args->getResponse()->appendBody(
99
                $this->variables->prependDataLayer('', $this->pluginConfig('wbmTagManagerJsonPrettyPrint'))
100
            );
101
        }
102
    }
103
104
    /**
105
     * @param \Enlight_Controller_ActionEventArgs $args
106
     *
107
     * @throws \Exception
108
     */
109
    public function onPreDispatch(\Enlight_Controller_ActionEventArgs $args)
110
    {
111
        $this->getParametersForSession($args->getRequest());
112
        $this->handleDispatch($args, true);
113
    }
114
115
    /**
116
     * @param \Enlight_Controller_ActionEventArgs $args
117
     *
118
     * @throws \Exception
119
     */
120
    public function onWidgetsPreDispatch(\Enlight_Controller_ActionEventArgs $args)
121
    {
122
        $this->getParametersForSession($args->getRequest());
123
        $this->onWidgetsPostDispatch($args, true);
124
    }
125
126
    /**
127
     * @param \Enlight_Controller_ActionEventArgs $args
128
     * @param bool                                $isPreDispatch
129
     *
130
     * @throws \Exception
131
     *
132
     * @return string|null
133
     */
134
    public function handleDispatch(
135
        \Enlight_Controller_ActionEventArgs $args,
136
        $isPreDispatch = false
137
    ) {
138
        if (
139
            !$this->pluginConfig('wbmTagManagerActive') ||
140
            empty($this->pluginConfig('wbmTagManagerContainer'))
141
        ) {
142
            return null;
143
        }
144
145
        $controller = $args->getSubject();
146
        $request = $controller->Request();
147
148
        $module = $oModule = join('_', [
149
                strtolower($request->getModuleName()),
150
                strtolower($request->getControllerName()),
151
                strtolower($request->getActionName()),
152
            ]);
153
154
        $module = $this->rewriteModuleKey(
155
            $module,
156
            $request->getParam('action'),
157
            $request->isDispatched()
158
        );
159
160
        if (!isset($this->modules[$module]) || $this->modules[$module] !== $isPreDispatch) {
161
            return null;
162
        }
163
164
        $this->variables->setModule($request->getModuleName());
165
        if (!$this->variables->getVariables()) {
166
            $this->variables->setViewVariables($controller->View()->getAssign());
167
            $this->variables->render($module);
168
        }
169
170
        // Since SW 5.3 the generic listingCountAction is used for paginated listings.
171
        // Get the response json body, decode it, prepend the dataLayer to the listing key
172
        // and set json encoded markup as response body.
173
        if ($oModule == 'widgets_listing_listingcount') {
174
            /** @var \Enlight_Controller_Response_ResponseHttp $response */
175
            $response = $controller->Response();
176
            $data = json_decode($response->getBody(), true);
177
178
            if (isset($data['listing'])) {
179
                if ($this->variables->getVariables()) {
180
                    $data['listing'] = $this->variables->prependDataLayer(
181
                        $data['listing'],
182
                        $this->pluginConfig('wbmTagManagerJsonPrettyPrint')
183
                    );
184
185
                    $response->setBody(json_encode($data));
186
                }
187
            }
188
        }
189
190
        return $oModule;
191
    }
192
193
    /**
194
     * @param string $module
195
     * @param string $action
196
     * @param bool   $isDispatched
197
     *
198
     * @return string
199
     */
200
    private function rewriteModuleKey(
201
        $module,
202
        $action,
203
        $isDispatched
204
    ) {
205
        if ($module == 'frontend_checkout_ajaxcart') {
206
            $module = 'frontend_checkout_' . strtolower($action);
207
        }
208
209
        if ($module == 'frontend_search_defaultsearch' && !$isDispatched) {
210
            $module = 'frontend_search_index';
211
        }
212
213
        $search = [
214
            'widgets_listing_ajaxlisting',
215
            'widgets_listing_listingcount',
216
            'frontend_checkout_ajaxcart',
217
            'frontend_checkout_ajax_add_article',
218
            'frontend_checkout_ajax_delete_article',
219
            'frontend_checkout_deletearticle',
220
        ];
221
222
        $replace = [
223
            'frontend_listing_index',
224
            'frontend_listing_index',
225
            'frontend_checkout_cart',
226
            'frontend_checkout_ajaxaddarticlecart',
227
            'frontend_checkout_ajaxdeletearticlecart',
228
            'frontend_checkout_ajaxdeletearticlecart',
229
        ];
230
231
        return str_replace($search, $replace, $module);
232
    }
233
234
    /**
235
     * @param \Enlight_Controller_Request_Request $request
236
     */
237
    private function getParametersForSession(\Enlight_Controller_Request_Request $request)
238
    {
239
        $parameters = $this->pluginConfig('wbmSessionParameters');
240
241
        if (empty($parameters)) {
242
            return;
243
        }
244
245
        $parameters = explode(',', $parameters);
246
        $session = $this->session->offsetGet('wbmTagManager') ?: [];
247
248
        foreach ($parameters as $parameter) {
249
            $parameter = trim($parameter);
250
            $value = $request->getParam($parameter);
251
252
            if (empty($value)) {
253
                continue;
254
            }
255
256
            $session[$parameter] = $value;
257
        }
258
259
        $this->session->offsetSet('wbmTagManager', $session);
260
    }
261
}
262