Completed
Pull Request — master (#358)
by Simon
03:44
created

getSubscribersForVerifiedKeys()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 10
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 15
rs 9.4285
1
<?php
2
/**
3
 * (c) shopware AG <[email protected]>
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
8
namespace ShopwarePlugins\Connect\Bootstrap;
9
10
use Enlight_Components_Db_Adapter_Pdo_Mysql;
11
use Shopware\Components\Model\ModelManager;
12
use Shopware\Connect\Gateway\PDO;
13
use Shopware\Connect\SDK;
14
use ShopwarePlugins\Connect\Components\Config;
15
use ShopwarePlugins\Connect\Components\ConnectFactory;
16
use ShopwarePlugins\Connect\Components\Helper;
17
use ShopwarePlugins\Connect\Subscribers\Checkout;
18
use ShopwarePlugins\Connect\Subscribers\Lifecycle;
19
use Symfony\Component\DependencyInjection\Container;
20
21
class SubscriberRegistration
22
{
23
    /**
24
     * @var ModelManager
25
     */
26
    private $modelManager;
27
28
    /**
29
     * @var Config
30
     */
31
    private $config;
32
33
    /**
34
     * @var Enlight_Components_Db_Adapter_Pdo_Mysql
35
     */
36
    private $db;
37
38
    /**
39
     * @TODO: Subscribers should not depend on the Bootstrap class. If you see a possible solution refactor it please.
40
     *
41
     * @var \Shopware_Plugins_Backend_SwagConnect_Bootstrap
42
     */
43
    private $pluginBootstrap;
44
45
    /**
46
     * @var \Enlight_Event_EventManager
47
     */
48
    private $eventManager;
49
50
    /**
51
     * @var SDK
52
     */
53
    private $SDK;
54
55
    /**
56
     * @var ConnectFactory
57
     */
58
    private $connectFactory;
59
60
    /**
61
     * @var Helper
62
     */
63
    private $helper;
64
65
    /**
66
     * This property saves all product updates and will be inserted back later
67
     *
68
     * @var array
69
     */
70
    private $productUpdates = [];
71
72
    /**
73
     * @var Lifecycle
74
     */
75
    private $lifecycle;
76
77
    /**
78
     * @var Container
79
     */
80
    private $container;
81
82
    /**
83
     * @param Config $config
84
     * @param ModelManager $modelManager
85
     * @param Enlight_Components_Db_Adapter_Pdo_Mysql $db
86
     * @param \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap
87
     * @param \Enlight_Event_EventManager $eventManager
88
     * @param SDK $SDK
89
     * @param ConnectFactory $connectFactory
90
     * @param Helper $helper
91
     * @param Container $container
92
     */
93 View Code Duplication
    public function __construct(
0 ignored issues
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...
94
        Config $config,
95
        ModelManager $modelManager,
96
        Enlight_Components_Db_Adapter_Pdo_Mysql $db,
97
        \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap,
98
        \Enlight_Event_EventManager $eventManager,
99
        SDK $SDK,
100
        ConnectFactory $connectFactory,
101
        Helper $helper,
102
        Container $container
103
    ) {
104
        $this->config = $config;
105
        $this->modelManager = $modelManager;
106
        $this->db = $db;
107
        $this->pluginBootstrap = $pluginBootstrap;
108
        $this->eventManager = $eventManager;
109
        $this->SDK = $SDK;
110
        $this->connectFactory = $connectFactory;
111
        $this->helper = $helper;
112
        $this->container = $container;
113
    }
114
115
    public function registerSubscribers()
116
    {
117
        try {
118
            $verified = $this->config->getConfig('apiKeyVerified', false);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $verified is correct as $this->config->getConfig('apiKeyVerified', false) (which targets ShopwarePlugins\Connect\...nts\Config::getConfig()) seems to always return null.

This check looks for function or method calls that always return null and whose return value is assigned to a variable.

class A
{
    function getObject()
    {
        return null;
    }

}

$a = new A();
$object = $a->getObject();

The method getObject() can return nothing but null, so it makes no sense to assign that value to a variable.

The reason is most likely that a function or method is imcomplete or has been reduced for debug purposes.

Loading history...
119
        } catch (\Exception $e) {
120
            // if the config table is not available, just assume, that the update
121
            // still needs to be installed
122
            $verified = false;
123
        }
124
125
        $subscribers = $this->getDefaultSubscribers();
126
        $newSubscribers = $this->getNewSubscribers();
127
128
        // Some subscribers may only be used, if the SDK is verified
129
        if ($verified) {
130
            $subscribers = array_merge($subscribers, $this->getSubscribersForVerifiedKeys());
131
132
            $newSubscribers = array_merge($newSubscribers, [
133
                new \ShopwarePlugins\Connect\Subscribers\BasketWidget(
134
                    $this->pluginBootstrap->getBasketHelper(),
135
                    $this->helper
136
                ),
137
            ]);
138
            // These subscribers are used if the api key is not valid
139
        } else {
140
            $subscribers = array_merge($subscribers, $this->getSubscribersForUnverifiedKeys());
141
        }
142
143
        $this->eventManager->addSubscriber(...$newSubscribers);
144
145
        /** @var $subscriber \ShopwarePlugins\Connect\Subscribers\BaseSubscriber */
146
        foreach ($subscribers as $subscriber) {
147
            $subscriber->setBootstrap($this->pluginBootstrap);
148
            $this->eventManager->registerSubscriber($subscriber);
149
        }
150
151
        $this->modelManager->getEventManager()->addEventListener(
152
            [\Doctrine\ORM\Events::onFlush, \Doctrine\ORM\Events::postFlush],
153
            $this
154
        );
155
    }
156
157
    /**
158
     * @return array
159
     */
160
    private function getNewSubscribers()
161
    {
162
        return [
163
            new \ShopwarePlugins\Connect\Subscribers\Article(
164
                new PDO($this->db->getConnection()),
165
                $this->modelManager,
166
                $this->connectFactory->getConnectExport(),
167
                $this->helper,
168
                $this->config,
169
                $this->connectFactory->getSDK(),
170
                $this->container->get('snippets'),
171
                $this->pluginBootstrap->Path()
172
            ),
173
            new \ShopwarePlugins\Connect\Subscribers\ArticleList(
174
                $this->pluginBootstrap->Path(),
175
                $this->container->get('snippets')
176
            ),
177
        ];
178
    }
179
180
    /**
181
     * Default subscribers can safely be used, even if the api key wasn't verified, yet
182
     *
183
     * @return array
184
     */
185
    private function getDefaultSubscribers()
186
    {
187
        return [
188
            new \ShopwarePlugins\Connect\Subscribers\OrderDocument(),
189
            new \ShopwarePlugins\Connect\Subscribers\ControllerPath(),
190
            new \ShopwarePlugins\Connect\Subscribers\CustomerGroup(),
191
            new \ShopwarePlugins\Connect\Subscribers\CronJob(
192
                $this->SDK,
193
                $this->connectFactory->getConnectExport()
194
            ),
195
            new \ShopwarePlugins\Connect\Subscribers\Category(
196
                $this->modelManager
197
            ),
198
            new \ShopwarePlugins\Connect\Subscribers\Connect(),
199
            new \ShopwarePlugins\Connect\Subscribers\Payment(),
200
            new \ShopwarePlugins\Connect\Subscribers\ServiceContainer(
201
                $this->modelManager,
202
                $this->db,
203
                $this->container
204
            ),
205
            new \ShopwarePlugins\Connect\Subscribers\Supplier(),
206
            new \ShopwarePlugins\Connect\Subscribers\ProductStreams(
207
                $this->connectFactory->getConnectExport(),
208
                new Config($this->modelManager),
209
                $this->helper
210
            ),
211
            new \ShopwarePlugins\Connect\Subscribers\Property(
212
                $this->modelManager
213
            ),
214
            new \ShopwarePlugins\Connect\Subscribers\Search(
215
                $this->modelManager
216
            ),
217
        ];
218
    }
219
220
    /**
221
     * @return array
222
     */
223
    private function getSubscribersForUnverifiedKeys()
224
    {
225
        return [
226
            new \ShopwarePlugins\Connect\Subscribers\DisableConnectInFrontend(),
227
            $this->getLifecycleSubscriber()
228
        ];
229
    }
230
231
    /**
232
     * These subscribers will only be used, once the user has verified his api key
233
     * This will prevent the users from having shopware Connect extensions in their frontend
234
     * even if they cannot use shopware Connect due to the missing / wrong api key
235
     *
236
     * @return array
237
     */
238
    private function getSubscribersForVerifiedKeys()
239
    {
240
        $subscribers = [
241
            new \ShopwarePlugins\Connect\Subscribers\TemplateExtension(),
242
            $this->createCheckoutSubscriber(),
243
            new \ShopwarePlugins\Connect\Subscribers\Voucher(),
244
            new \ShopwarePlugins\Connect\Subscribers\Dispatches(),
245
            new \ShopwarePlugins\Connect\Subscribers\Javascript(),
246
            new \ShopwarePlugins\Connect\Subscribers\Less(),
247
            $this->getLifecycleSubscriber()
248
249
        ];
250
251
        return $subscribers;
252
    }
253
254
    /**
255
     * Creates checkout subscriber
256
     *
257
     * @return Checkout
258
     */
259
    private function createCheckoutSubscriber()
260
    {
261
        $checkoutSubscriber = new Checkout(
262
            $this->modelManager,
263
            $this->eventManager
264
        );
265
        foreach ($checkoutSubscriber->getListeners() as $listener) {
266
            if ($listener->getName() === 'Enlight_Controller_Action_PostDispatch_Frontend_Checkout') {
267
                $listener->setPosition(-1);
268
            }
269
        }
270
271
        return $checkoutSubscriber;
272
    }
273
274
    /**
275
     * Generate changes for updated Articles and Details.
276
     * On postFlush all related entities are updated and product can
277
     * be fetched from DB correctly.
278
     *
279
     * @param \Doctrine\ORM\Event\PostFlushEventArgs $eventArgs
280
     */
281
    public function postFlush(\Doctrine\ORM\Event\PostFlushEventArgs $eventArgs)
0 ignored issues
show
Unused Code introduced by
The parameter $eventArgs is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
282
    {
283
        foreach ($this->productUpdates as $entity) {
284
            $this->getLifecycleSubscriber()->handleChange($entity);
285
        }
286
287
        $this->productUpdates = [];
288
    }
289
290
    /**
291
     * @return Lifecycle
292
     */
293
    private function getLifecycleSubscriber()
294
    {
295
        if (!$this->lifecycle) {
296
            $this->lifecycle = new Lifecycle(
297
                $this->modelManager,
298
                $this->config->getConfig('autoUpdateProducts', 1)
299
            );
300
        }
301
302
        return $this->lifecycle;
303
    }
304
305
    /**
306
     * Collect updated Articles and Details
307
     * Lifecycle events don't work correctly, because products will be fetched via query builder,
308
     * but related entities like price are not updated yet.
309
     *
310
     * @param \Doctrine\ORM\Event\OnFlushEventArgs $eventArgs
311
     */
312
    public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $eventArgs)
313
    {
314
        /** @var $em ModelManager */
315
        $em  = $eventArgs->getEntityManager();
316
        $uow = $em->getUnitOfWork();
317
318
        // Entity updates
319
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
320
            if (!$entity instanceof \Shopware\Models\Article\Article
0 ignored issues
show
Bug introduced by
The class Shopware\Models\Article\Article does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
321
                && !$entity instanceof \Shopware\Models\Article\Detail
0 ignored issues
show
Bug introduced by
The class Shopware\Models\Article\Detail does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
322
            ) {
323
                continue;
324
            }
325
326
            $this->productUpdates[] = $entity;
327
        }
328
    }
329
}
330