Completed
Pull Request — master (#358)
by Simon
04:22
created

SubscriberRegistration::getNewSubscribers()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 40
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 31
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 40
rs 8.8571
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\ControllerPath;
22
use ShopwarePlugins\Connect\Subscribers\Lifecycle;
23
use Symfony\Component\DependencyInjection\Container;
24
25
class SubscriberRegistration
26
{
27
    /**
28
     * @var ModelManager
29
     */
30
    private $modelManager;
31
32
    /**
33
     * @var Config
34
     */
35
    private $config;
36
37
    /**
38
     * @var Enlight_Components_Db_Adapter_Pdo_Mysql
39
     */
40
    private $db;
41
42
    /**
43
     * @TODO: Subscribers should not depend on the Bootstrap class. If you see a possible solution refactor it please.
44
     *
45
     * @var \Shopware_Plugins_Backend_SwagConnect_Bootstrap
46
     */
47
    private $pluginBootstrap;
48
49
    /**
50
     * @var \Enlight_Event_EventManager
51
     */
52
    private $eventManager;
53
54
    /**
55
     * @var SDK
56
     */
57
    private $SDK;
58
59
    /**
60
     * @var ConnectFactory
61
     */
62
    private $connectFactory;
63
64
    /**
65
     * @var Helper
66
     */
67
    private $helper;
68
69
    /**
70
     * This property saves all product updates and will be inserted back later
71
     *
72
     * @var array
73
     */
74
    private $productUpdates = [];
75
76
    /**
77
     * @var Lifecycle
78
     */
79
    private $lifecycle;
80
81
    /**
82
     * @var Container
83
     */
84
    private $container;
85
86
    /**
87
     * @param Config $config
88
     * @param ModelManager $modelManager
89
     * @param Enlight_Components_Db_Adapter_Pdo_Mysql $db
90
     * @param \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap
91
     * @param \Enlight_Event_EventManager $eventManager
92
     * @param SDK $SDK
93
     * @param ConnectFactory $connectFactory
94
     * @param Helper $helper
95
     * @param Container $container
96
     */
97 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...
Coding Style Naming introduced by
The parameter $SDK is not named in camelCase.

This check marks parameter names that have not been written in camelCase.

In camelCase names are written without any punctuation, the start of each new word being marked by a capital letter. Thus the name database connection string becomes databaseConnectionString.

Loading history...
98
        Config $config,
99
        ModelManager $modelManager,
100
        Enlight_Components_Db_Adapter_Pdo_Mysql $db,
101
        \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap,
102
        \Enlight_Event_EventManager $eventManager,
103
        SDK $SDK,
104
        ConnectFactory $connectFactory,
105
        Helper $helper,
106
        Container $container
107
    ) {
108
        $this->config = $config;
109
        $this->modelManager = $modelManager;
110
        $this->db = $db;
111
        $this->pluginBootstrap = $pluginBootstrap;
112
        $this->eventManager = $eventManager;
113
        $this->SDK = $SDK;
114
        $this->connectFactory = $connectFactory;
115
        $this->helper = $helper;
116
        $this->container = $container;
117
    }
118
119
    public function registerSubscribers()
120
    {
121
        try {
122
            $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...
123
        } catch (\Exception $e) {
124
            // if the config table is not available, just assume, that the update
125
            // still needs to be installed
126
            $verified = false;
127
        }
128
129
        $subscribers = $this->getDefaultSubscribers();
130
        $newSubscribers = $this->getNewSubscribers();
131
132
        // Some subscribers may only be used, if the SDK is verified
133
        if ($verified) {
134
            $subscribers = array_merge($subscribers, $this->getSubscribersForVerifiedKeys());
135
136
            $newSubscribers = array_merge($newSubscribers, [
137
                new \ShopwarePlugins\Connect\Subscribers\BasketWidget(
138
                    $this->pluginBootstrap->getBasketHelper(),
139
                    $this->helper
140
                ),
141
                $checkoutSubscriber = new Checkout(
142
                    $this->modelManager,
143
                    $this->eventManager,
144
                    $this->connectFactory->getSDK(),
145
                    $this->connectFactory->getBasketHelper(),
146
                    $this->connectFactory->getHelper()
147
                )
148
            ]);
149
            // These subscribers are used if the api key is not valid
150
        } else {
151
            $subscribers = array_merge($subscribers, $this->getSubscribersForUnverifiedKeys());
152
        }
153
154
        foreach ($newSubscribers as $newSubscriber) {
155
            $this->eventManager->addSubscriber($newSubscriber);
156
        }
157
158
        /** @var $subscriber \ShopwarePlugins\Connect\Subscribers\BaseSubscriber */
159
        foreach ($subscribers as $subscriber) {
160
            $subscriber->setBootstrap($this->pluginBootstrap);
161
            $this->eventManager->registerSubscriber($subscriber);
162
        }
163
164
        $this->modelManager->getEventManager()->addEventListener(
165
            [\Doctrine\ORM\Events::onFlush, \Doctrine\ORM\Events::postFlush],
166
            $this
167
        );
168
    }
169
170
    /**
171
     * @return array
172
     */
173
    private function getNewSubscribers()
174
    {
175
        return [
176
            new \ShopwarePlugins\Connect\Subscribers\Article(
177
                new PDO($this->db->getConnection()),
178
                $this->modelManager,
179
                $this->connectFactory->getConnectExport(),
180
                $this->helper,
181
                $this->config,
182
                $this->connectFactory->getSDK(),
183
                $this->container->get('snippets'),
184
                $this->pluginBootstrap->Path()
185
            ),
186
            new \ShopwarePlugins\Connect\Subscribers\ArticleList(
187
                $this->pluginBootstrap->Path(),
188
                $this->container->get('snippets')
189
            ),
190
            new \ShopwarePlugins\Connect\Subscribers\Category(
191
                $this->container->get('dbal_connection'),
192
                $this->createProductStreamService()
193
            ),
194
            new \ShopwarePlugins\Connect\Subscribers\Connect(
195
                $this->config,
196
                $this->SDK,
197
                $this->container->get('snippets'),
198
                $this->pluginBootstrap->Path()
199
            ),
200
            new ControllerPath(
201
                $this->pluginBootstrap->Path(),
202
                $this->container,
203
                $this->container->get('snippets')
204
            ),
205
            new \ShopwarePlugins\Connect\Subscribers\CronJob(
206
                $this->SDK,
207
                $this->connectFactory->getConnectExport(),
208
                $this->config,
209
                $this->helper
210
            ),
211
        ];
212
    }
213
214
    /**
215
     * Default subscribers can safely be used, even if the api key wasn't verified, yet
216
     *
217
     * @return array
218
     */
219
    private function getDefaultSubscribers()
220
    {
221
        return [
222
            new \ShopwarePlugins\Connect\Subscribers\OrderDocument(),
223
            new \ShopwarePlugins\Connect\Subscribers\CustomerGroup(),
224
            new \ShopwarePlugins\Connect\Subscribers\Payment(),
225
            new \ShopwarePlugins\Connect\Subscribers\ServiceContainer(
226
                $this->modelManager,
227
                $this->db,
228
                $this->container
229
            ),
230
            new \ShopwarePlugins\Connect\Subscribers\Supplier(),
231
            new \ShopwarePlugins\Connect\Subscribers\ProductStreams(
232
                $this->connectFactory->getConnectExport(),
233
                new Config($this->modelManager),
234
                $this->helper
235
            ),
236
            new \ShopwarePlugins\Connect\Subscribers\Property(
237
                $this->modelManager
238
            ),
239
            new \ShopwarePlugins\Connect\Subscribers\Search(
240
                $this->modelManager
241
            ),
242
        ];
243
    }
244
245
    /**
246
     * @return array
247
     */
248
    private function getSubscribersForUnverifiedKeys()
249
    {
250
        return [
251
            new \ShopwarePlugins\Connect\Subscribers\DisableConnectInFrontend(),
252
            $this->getLifecycleSubscriber()
253
        ];
254
    }
255
256
    /**
257
     * These subscribers will only be used, once the user has verified his api key
258
     * This will prevent the users from having shopware Connect extensions in their frontend
259
     * even if they cannot use shopware Connect due to the missing / wrong api key
260
     *
261
     * @return array
262
     */
263
    private function getSubscribersForVerifiedKeys()
264
    {
265
        $subscribers = [
266
            new \ShopwarePlugins\Connect\Subscribers\TemplateExtension(),
267
            new \ShopwarePlugins\Connect\Subscribers\Voucher(),
268
            new \ShopwarePlugins\Connect\Subscribers\Dispatches(),
269
            new \ShopwarePlugins\Connect\Subscribers\Javascript(),
270
            new \ShopwarePlugins\Connect\Subscribers\Less(),
271
            $this->getLifecycleSubscriber()
272
273
        ];
274
275
        return $subscribers;
276
    }
277
278
    /**
279
     * Generate changes for updated Articles and Details.
280
     * On postFlush all related entities are updated and product can
281
     * be fetched from DB correctly.
282
     *
283
     * @param \Doctrine\ORM\Event\PostFlushEventArgs $eventArgs
284
     */
285
    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...
286
    {
287
        foreach ($this->productUpdates as $entity) {
288
            $this->getLifecycleSubscriber()->handleChange($entity);
289
        }
290
291
        $this->productUpdates = [];
292
    }
293
294
    /**
295
     * @return Lifecycle
296
     */
297
    private function getLifecycleSubscriber()
298
    {
299
        if (!$this->lifecycle) {
300
            $this->lifecycle = new Lifecycle(
301
                $this->modelManager,
302
                $this->config->getConfig('autoUpdateProducts', 1)
303
            );
304
        }
305
306
        return $this->lifecycle;
307
    }
308
309
    /**
310
     * Collect updated Articles and Details
311
     * Lifecycle events don't work correctly, because products will be fetched via query builder,
312
     * but related entities like price are not updated yet.
313
     *
314
     * @param \Doctrine\ORM\Event\OnFlushEventArgs $eventArgs
315
     */
316
    public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $eventArgs)
317
    {
318
        /** @var $em ModelManager */
319
        $em  = $eventArgs->getEntityManager();
320
        $uow = $em->getUnitOfWork();
321
322
        // Entity updates
323
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
324
            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...
325
                && !$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...
326
            ) {
327
                continue;
328
            }
329
330
            $this->productUpdates[] = $entity;
331
        }
332
    }
333
334
    /**
335
     * @return ProductStreamService
336
     */
337 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...
338
    {
339
        /** @var ProductStreamAttributeRepository $streamAttrRepository */
340
        $streamAttrRepository = $this->modelManager->getRepository('Shopware\CustomModels\Connect\ProductStreamAttribute');
341
342
        return new ProductStreamService(
343
            new ProductStreamRepository($this->modelManager, $this->container->get('shopware_product_stream.repository')),
344
            $streamAttrRepository,
345
            new Config($this->modelManager),
346
            $this->container->get('shopware_search.product_search'),
347
            $this->container->get('shopware_storefront.context_service')
348
        );
349
    }
350
}
351