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

getSubscribersForVerifiedKeys()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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