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

SubscriberRegistration::getDefaultSubscribers()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 1
eloc 11
c 2
b 0
f 0
nc 1
nop 0
dl 0
loc 17
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 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\Logger;
19
use ShopwarePlugins\Connect\Components\ProductStream\ProductStreamRepository;
20
use ShopwarePlugins\Connect\Components\ProductStream\ProductStreamService;
21
use ShopwarePlugins\Connect\Subscribers\Checkout;
22
use ShopwarePlugins\Connect\Subscribers\ControllerPath;
23
use ShopwarePlugins\Connect\Subscribers\CustomerGroup;
24
use ShopwarePlugins\Connect\Subscribers\Lifecycle;
25
use Symfony\Component\DependencyInjection\Container;
26
27
class SubscriberRegistration
28
{
29
    /**
30
     * @var ModelManager
31
     */
32
    private $modelManager;
33
34
    /**
35
     * @var Config
36
     */
37
    private $config;
38
39
    /**
40
     * @var Enlight_Components_Db_Adapter_Pdo_Mysql
41
     */
42
    private $db;
43
44
    /**
45
     * @TODO: Subscribers should not depend on the Bootstrap class. If you see a possible solution refactor it please.
46
     *
47
     * @var \Shopware_Plugins_Backend_SwagConnect_Bootstrap
48
     */
49
    private $pluginBootstrap;
50
51
    /**
52
     * @var \Enlight_Event_EventManager
53
     */
54
    private $eventManager;
55
56
    /**
57
     * @var SDK
58
     */
59
    private $SDK;
60
61
    /**
62
     * @var ConnectFactory
63
     */
64
    private $connectFactory;
65
66
    /**
67
     * @var Helper
68
     */
69
    private $helper;
70
71
    /**
72
     * This property saves all product updates and will be inserted back later
73
     *
74
     * @var array
75
     */
76
    private $productUpdates = [];
77
78
    /**
79
     * @var Lifecycle
80
     */
81
    private $lifecycle;
82
83
    /**
84
     * @var Container
85
     */
86
    private $container;
87
88
    /**
89
     * @param Config $config
90
     * @param ModelManager $modelManager
91
     * @param Enlight_Components_Db_Adapter_Pdo_Mysql $db
92
     * @param \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap
93
     * @param \Enlight_Event_EventManager $eventManager
94
     * @param SDK $SDK
95
     * @param ConnectFactory $connectFactory
96
     * @param Helper $helper
97
     * @param Container $container
98
     */
99 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...
100
        Config $config,
101
        ModelManager $modelManager,
102
        Enlight_Components_Db_Adapter_Pdo_Mysql $db,
103
        \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap,
104
        \Enlight_Event_EventManager $eventManager,
105
        SDK $SDK,
106
        ConnectFactory $connectFactory,
107
        Helper $helper,
108
        Container $container
109
    ) {
110
        $this->config = $config;
111
        $this->modelManager = $modelManager;
112
        $this->db = $db;
113
        $this->pluginBootstrap = $pluginBootstrap;
114
        $this->eventManager = $eventManager;
115
        $this->SDK = $SDK;
116
        $this->connectFactory = $connectFactory;
117
        $this->helper = $helper;
118
        $this->container = $container;
119
    }
120
121
    public function registerSubscribers()
122
    {
123
        try {
124
            $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...
125
        } catch (\Exception $e) {
126
            // if the config table is not available, just assume, that the update
127
            // still needs to be installed
128
            $verified = false;
129
        }
130
131
        $subscribers = $this->getDefaultSubscribers();
132
        $newSubscribers = $this->getNewSubscribers();
133
134
        // Some subscribers may only be used, if the SDK is verified
135
        if ($verified) {
136
            $subscribers = array_merge($subscribers, $this->getSubscribersForVerifiedKeys());
137
138
            $newSubscribers = array_merge($newSubscribers, [
139
                new \ShopwarePlugins\Connect\Subscribers\BasketWidget(
140
                    $this->pluginBootstrap->getBasketHelper(),
141
                    $this->helper
142
                ),
143
                new Checkout(
144
                    $this->modelManager,
145
                    $this->eventManager,
146
                    $this->connectFactory->getSDK(),
147
                    $this->connectFactory->getBasketHelper(),
148
                    $this->connectFactory->getHelper()
149
                ),
150
                new \ShopwarePlugins\Connect\Subscribers\Dispatches(
151
                    $this->helper,
152
                    $this->pluginBootstrap->Path(),
153
                    $this->container->get('snippets')
154
                ),
155
                new \ShopwarePlugins\Connect\Subscribers\Javascript(),
156
                new \ShopwarePlugins\Connect\Subscribers\Less()
157
            ]);
158
            // These subscribers are used if the api key is not valid
159
        } else {
160
            $newSubscribers = array_merge($newSubscribers, [
161
                new \ShopwarePlugins\Connect\Subscribers\DisableConnectInFrontend(
162
                    $this->pluginBootstrap->Path(), $this->container->get('db')
163
                )
164
            ]);
165
        }
166
167
        foreach ($newSubscribers as $newSubscriber) {
168
            $this->eventManager->addSubscriber($newSubscriber);
169
        }
170
171
        /** @var $subscriber \ShopwarePlugins\Connect\Subscribers\BaseSubscriber */
172
        foreach ($subscribers as $subscriber) {
173
            $subscriber->setBootstrap($this->pluginBootstrap);
174
            $this->eventManager->registerSubscriber($subscriber);
175
        }
176
177
        $this->modelManager->getEventManager()->addEventListener(
178
            [\Doctrine\ORM\Events::onFlush, \Doctrine\ORM\Events::postFlush],
179
            $this
180
        );
181
    }
182
183
    /**
184
     * @return array
185
     */
186
    private function getNewSubscribers()
187
    {
188
        return [
189
            new \ShopwarePlugins\Connect\Subscribers\Article(
190
                new PDO($this->db->getConnection()),
191
                $this->modelManager,
192
                $this->connectFactory->getConnectExport(),
193
                $this->helper,
194
                $this->config,
195
                $this->connectFactory->getSDK(),
196
                $this->container->get('snippets'),
197
                $this->pluginBootstrap->Path()
198
            ),
199
            new \ShopwarePlugins\Connect\Subscribers\ArticleList(
200
                $this->pluginBootstrap->Path(),
201
                $this->container->get('snippets')
202
            ),
203
            new \ShopwarePlugins\Connect\Subscribers\Category(
204
                $this->container->get('dbal_connection'),
205
                $this->createProductStreamService()
206
            ),
207
            new \ShopwarePlugins\Connect\Subscribers\Connect(
208
                $this->config,
209
                $this->SDK,
210
                $this->container->get('snippets'),
211
                $this->pluginBootstrap->Path()
212
            ),
213
            new ControllerPath(
214
                $this->pluginBootstrap->Path(),
215
                $this->container,
216
                $this->container->get('snippets')
217
            ),
218
            new \ShopwarePlugins\Connect\Subscribers\CronJob(
219
                $this->SDK,
220
                $this->connectFactory->getConnectExport(),
221
                $this->config,
222
                $this->helper
223
            ),
224
            new CustomerGroup(
225
                $this->modelManager,
226
                new Logger(Shopware()->Db())
227
            ),
228
            $this->getLifecycleSubscriber(),
229
            new \ShopwarePlugins\Connect\Subscribers\OrderDocument(),
230
            new \ShopwarePlugins\Connect\Subscribers\PaymentSubscriber(
231
                $this->pluginBootstrap->Path(),
232
                $this->helper
233
            ),
234
            new \ShopwarePlugins\Connect\Subscribers\ProductStreams(
235
                $this->connectFactory->getConnectExport(),
236
                new Config($this->modelManager),
237
                $this->helper,
238
                $this->SDK,
239
                $this->pluginBootstrap->Path(),
240
                $this->container->get('snippets')
241
            ),
242
        ];
243
    }
244
245
    /**
246
     * Default subscribers can safely be used, even if the api key wasn't verified, yet
247
     *
248
     * @return array
249
     */
250
    private function getDefaultSubscribers()
251
    {
252
        return [
253
            new \ShopwarePlugins\Connect\Subscribers\ServiceContainer(
254
                $this->modelManager,
255
                $this->db,
256
                $this->container
257
            ),
258
            new \ShopwarePlugins\Connect\Subscribers\Supplier(),
259
            new \ShopwarePlugins\Connect\Subscribers\Property(
260
                $this->modelManager
261
            ),
262
            new \ShopwarePlugins\Connect\Subscribers\Search(
263
                $this->modelManager
264
            ),
265
        ];
266
    }
267
268
    /**
269
     * These subscribers will only be used, once the user has verified his api key
270
     * This will prevent the users from having shopware Connect extensions in their frontend
271
     * even if they cannot use shopware Connect due to the missing / wrong api key
272
     *
273
     * @return array
274
     */
275
    private function getSubscribersForVerifiedKeys()
276
    {
277
        $subscribers = [
278
            new \ShopwarePlugins\Connect\Subscribers\TemplateExtension(),
279
            new \ShopwarePlugins\Connect\Subscribers\Voucher(),
280
281
        ];
282
283
        return $subscribers;
284
    }
285
286
    /**
287
     * Generate changes for updated Articles and Details.
288
     * On postFlush all related entities are updated and product can
289
     * be fetched from DB correctly.
290
     *
291
     * @param \Doctrine\ORM\Event\PostFlushEventArgs $eventArgs
292
     */
293
    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...
294
    {
295
        foreach ($this->productUpdates as $entity) {
296
            $this->getLifecycleSubscriber()->handleChange($entity);
297
        }
298
299
        $this->productUpdates = [];
300
    }
301
302
    /**
303
     * @return Lifecycle
304
     */
305
    private function getLifecycleSubscriber()
306
    {
307
        if (!$this->lifecycle) {
308
            $this->lifecycle = new Lifecycle(
309
                $this->modelManager,
310
                $this->config->getConfig('autoUpdateProducts', 1),
311
                $this->helper,
312
                $this->SDK,
313
                $this->config,
314
                $this->connectFactory->getConnectExport()
315
            );
316
        }
317
318
        return $this->lifecycle;
319
    }
320
321
    /**
322
     * Collect updated Articles and Details
323
     * Lifecycle events don't work correctly, because products will be fetched via query builder,
324
     * but related entities like price are not updated yet.
325
     *
326
     * @param \Doctrine\ORM\Event\OnFlushEventArgs $eventArgs
327
     */
328
    public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $eventArgs)
329
    {
330
        /** @var $em ModelManager */
331
        $em  = $eventArgs->getEntityManager();
332
        $uow = $em->getUnitOfWork();
333
334
        // Entity updates
335
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
336
            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...
337
                && !$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...
338
            ) {
339
                continue;
340
            }
341
342
            $this->productUpdates[] = $entity;
343
        }
344
    }
345
346
    /**
347
     * @return ProductStreamService
348
     */
349 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...
350
    {
351
        /** @var ProductStreamAttributeRepository $streamAttrRepository */
352
        $streamAttrRepository = $this->modelManager->getRepository('Shopware\CustomModels\Connect\ProductStreamAttribute');
353
354
        return new ProductStreamService(
355
            new ProductStreamRepository($this->modelManager, $this->container->get('shopware_product_stream.repository')),
356
            $streamAttrRepository,
357
            new Config($this->modelManager),
358
            $this->container->get('shopware_search.product_search'),
359
            $this->container->get('shopware_storefront.context_service')
360
        );
361
    }
362
}
363