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

SubscriberRegistration::getNewSubscribers()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 29
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

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