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

SubscriberRegistration::getNewSubscribers()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 34
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 22
nc 1
nop 0
dl 0
loc 34
rs 8.8571
c 0
b 0
f 0
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 Shopware\CustomModels\Connect\ProductStreamAttributeRepository;
15
use ShopwarePlugins\Connect\Components\Config;
16
use ShopwarePlugins\Connect\Components\ConnectFactory;
17
use ShopwarePlugins\Connect\Components\Helper;
18
use ShopwarePlugins\Connect\Components\ProductStream\ProductStreamRepository;
19
use ShopwarePlugins\Connect\Components\ProductStream\ProductStreamService;
20
use ShopwarePlugins\Connect\Subscribers\Checkout;
21
use ShopwarePlugins\Connect\Subscribers\Lifecycle;
22
use Symfony\Component\DependencyInjection\Container;
23
24
class SubscriberRegistration
25
{
26
    /**
27
     * @var ModelManager
28
     */
29
    private $modelManager;
30
31
    /**
32
     * @var Config
33
     */
34
    private $config;
35
36
    /**
37
     * @var Enlight_Components_Db_Adapter_Pdo_Mysql
38
     */
39
    private $db;
40
41
    /**
42
     * @TODO: Subscribers should not depend on the Bootstrap class. If you see a possible solution refactor it please.
43
     *
44
     * @var \Shopware_Plugins_Backend_SwagConnect_Bootstrap
45
     */
46
    private $pluginBootstrap;
47
48
    /**
49
     * @var \Enlight_Event_EventManager
50
     */
51
    private $eventManager;
52
53
    /**
54
     * @var SDK
55
     */
56
    private $SDK;
57
58
    /**
59
     * @var ConnectFactory
60
     */
61
    private $connectFactory;
62
63
    /**
64
     * @var Helper
65
     */
66
    private $helper;
67
68
    /**
69
     * This property saves all product updates and will be inserted back later
70
     *
71
     * @var array
72
     */
73
    private $productUpdates = [];
74
75
    /**
76
     * @var Lifecycle
77
     */
78
    private $lifecycle;
79
80
    /**
81
     * @var Container
82
     */
83
    private $container;
84
85
    /**
86
     * @param Config $config
87
     * @param ModelManager $modelManager
88
     * @param Enlight_Components_Db_Adapter_Pdo_Mysql $db
89
     * @param \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap
90
     * @param \Enlight_Event_EventManager $eventManager
91
     * @param SDK $SDK
92
     * @param ConnectFactory $connectFactory
93
     * @param Helper $helper
94
     * @param Container $container
95
     */
96 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...
97
        Config $config,
98
        ModelManager $modelManager,
99
        Enlight_Components_Db_Adapter_Pdo_Mysql $db,
100
        \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap,
101
        \Enlight_Event_EventManager $eventManager,
102
        SDK $SDK,
103
        ConnectFactory $connectFactory,
104
        Helper $helper,
105
        Container $container
106
    ) {
107
        $this->config = $config;
108
        $this->modelManager = $modelManager;
109
        $this->db = $db;
110
        $this->pluginBootstrap = $pluginBootstrap;
111
        $this->eventManager = $eventManager;
112
        $this->SDK = $SDK;
113
        $this->connectFactory = $connectFactory;
114
        $this->helper = $helper;
115
        $this->container = $container;
116
    }
117
118
    public function registerSubscribers()
119
    {
120
        try {
121
            $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...
122
        } catch (\Exception $e) {
123
            // if the config table is not available, just assume, that the update
124
            // still needs to be installed
125
            $verified = false;
126
        }
127
128
        $subscribers = $this->getDefaultSubscribers();
129
        $newSubscribers = $this->getNewSubscribers();
130
131
        // Some subscribers may only be used, if the SDK is verified
132
        if ($verified) {
133
            $subscribers = array_merge($subscribers, $this->getSubscribersForVerifiedKeys());
134
135
            $newSubscribers = array_merge($newSubscribers, [
136
                new \ShopwarePlugins\Connect\Subscribers\BasketWidget(
137
                    $this->pluginBootstrap->getBasketHelper(),
138
                    $this->helper
139
                ),
140
                $checkoutSubscriber = new Checkout(
141
                    $this->modelManager,
142
                    $this->eventManager,
143
                    $this->connectFactory->getSDK(),
144
                    $this->connectFactory->getBasketHelper(),
145
                    $this->connectFactory->getHelper()
146
                )
147
            ]);
148
            // These subscribers are used if the api key is not valid
149
        } else {
150
            $subscribers = array_merge($subscribers, $this->getSubscribersForUnverifiedKeys());
151
        }
152
153
        $this->eventManager->addSubscriber(...$newSubscribers);
154
155
        /** @var $subscriber \ShopwarePlugins\Connect\Subscribers\BaseSubscriber */
156
        foreach ($subscribers as $subscriber) {
157
            $subscriber->setBootstrap($this->pluginBootstrap);
158
            $this->eventManager->registerSubscriber($subscriber);
159
        }
160
161
        $this->modelManager->getEventManager()->addEventListener(
162
            [\Doctrine\ORM\Events::onFlush, \Doctrine\ORM\Events::postFlush],
163
            $this
164
        );
165
    }
166
167
    /**
168
     * @return array
169
     */
170
    private function getNewSubscribers()
171
    {
172
        return [
173
            new \ShopwarePlugins\Connect\Subscribers\Article(
174
                new PDO($this->db->getConnection()),
175
                $this->modelManager,
176
                $this->connectFactory->getConnectExport(),
177
                $this->helper,
178
                $this->config,
179
                $this->connectFactory->getSDK(),
180
                $this->container->get('snippets'),
181
                $this->pluginBootstrap->Path()
182
            ),
183
            new \ShopwarePlugins\Connect\Subscribers\ArticleList(
184
                $this->pluginBootstrap->Path(),
185
                $this->container->get('snippets')
186
            ),
187
            new \ShopwarePlugins\Connect\Subscribers\Category(
188
                $this->container->get('dbal_connection'),
189
                $this->createProductStreamService()
190
            ),
191
            new \ShopwarePlugins\Connect\Subscribers\Connect(
192
                $this->config,
193
                $this->SDK,
194
                $this->container->get('snippets'),
195
                $this->pluginBootstrap->Path()
196
            ),
197
//            new \ShopwarePlugins\Connect\Subscribers\ControllerPath(
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
198
//                $this->pluginBootstrap->Path(),
199
//                $this->container,
200
//                $this->container->get('snippets')
201
//            ),
202
        ];
203
    }
204
205
    /**
206
     * Default subscribers can safely be used, even if the api key wasn't verified, yet
207
     *
208
     * @return array
209
     */
210
    private function getDefaultSubscribers()
211
    {
212
        return [
213
            new \ShopwarePlugins\Connect\Subscribers\OrderDocument(),
214
            new \ShopwarePlugins\Connect\Subscribers\CustomerGroup(),
215
            new \ShopwarePlugins\Connect\Subscribers\CronJob(
216
                $this->SDK,
217
                $this->connectFactory->getConnectExport()
218
            ),
219
            new \ShopwarePlugins\Connect\Subscribers\Payment(),
220
            new \ShopwarePlugins\Connect\Subscribers\ServiceContainer(
221
                $this->modelManager,
222
                $this->db,
223
                $this->container
224
            ),
225
            new \ShopwarePlugins\Connect\Subscribers\Supplier(),
226
            new \ShopwarePlugins\Connect\Subscribers\ProductStreams(
227
                $this->connectFactory->getConnectExport(),
228
                new Config($this->modelManager),
229
                $this->helper
230
            ),
231
            new \ShopwarePlugins\Connect\Subscribers\Property(
232
                $this->modelManager
233
            ),
234
            new \ShopwarePlugins\Connect\Subscribers\Search(
235
                $this->modelManager
236
            ),
237
        ];
238
    }
239
240
    /**
241
     * @return array
242
     */
243
    private function getSubscribersForUnverifiedKeys()
244
    {
245
        return [
246
            new \ShopwarePlugins\Connect\Subscribers\DisableConnectInFrontend(),
247
            $this->getLifecycleSubscriber()
248
        ];
249
    }
250
251
    /**
252
     * These subscribers will only be used, once the user has verified his api key
253
     * This will prevent the users from having shopware Connect extensions in their frontend
254
     * even if they cannot use shopware Connect due to the missing / wrong api key
255
     *
256
     * @return array
257
     */
258
    private function getSubscribersForVerifiedKeys()
259
    {
260
        $subscribers = [
261
            new \ShopwarePlugins\Connect\Subscribers\TemplateExtension(),
262
            new \ShopwarePlugins\Connect\Subscribers\Voucher(),
263
            new \ShopwarePlugins\Connect\Subscribers\Dispatches(),
264
            new \ShopwarePlugins\Connect\Subscribers\Javascript(),
265
            new \ShopwarePlugins\Connect\Subscribers\Less(),
266
            $this->getLifecycleSubscriber()
267
268
        ];
269
270
        return $subscribers;
271
    }
272
273
    /**
274
     * Generate changes for updated Articles and Details.
275
     * On postFlush all related entities are updated and product can
276
     * be fetched from DB correctly.
277
     *
278
     * @param \Doctrine\ORM\Event\PostFlushEventArgs $eventArgs
279
     */
280
    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...
281
    {
282
        foreach ($this->productUpdates as $entity) {
283
            $this->getLifecycleSubscriber()->handleChange($entity);
284
        }
285
286
        $this->productUpdates = [];
287
    }
288
289
    /**
290
     * @return Lifecycle
291
     */
292
    private function getLifecycleSubscriber()
293
    {
294
        if (!$this->lifecycle) {
295
            $this->lifecycle = new Lifecycle(
296
                $this->modelManager,
297
                $this->config->getConfig('autoUpdateProducts', 1)
298
            );
299
        }
300
301
        return $this->lifecycle;
302
    }
303
304
    /**
305
     * Collect updated Articles and Details
306
     * Lifecycle events don't work correctly, because products will be fetched via query builder,
307
     * but related entities like price are not updated yet.
308
     *
309
     * @param \Doctrine\ORM\Event\OnFlushEventArgs $eventArgs
310
     */
311
    public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $eventArgs)
312
    {
313
        /** @var $em ModelManager */
314
        $em  = $eventArgs->getEntityManager();
315
        $uow = $em->getUnitOfWork();
316
317
        // Entity updates
318
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
319
            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...
320
                && !$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...
321
            ) {
322
                continue;
323
            }
324
325
            $this->productUpdates[] = $entity;
326
        }
327
    }
328
329
    /**
330
     * @return ProductStreamService
331
     */
332 View Code Duplication
    private function createProductStreamService()
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...
333
    {
334
        /** @var ProductStreamAttributeRepository $streamAttrRepository */
335
        $streamAttrRepository = $this->modelManager->getRepository('Shopware\CustomModels\Connect\ProductStreamAttribute');
336
337
        return new ProductStreamService(
338
            new ProductStreamRepository($this->modelManager, $this->container->get('shopware_product_stream.repository')),
339
            $streamAttrRepository,
340
            new Config($this->modelManager),
341
            $this->container->get('shopware_search.product_search'),
342
            $this->container->get('shopware_storefront.context_service')
343
        );
344
    }
345
}
346