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

SubscriberRegistration::onFlush()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 17
rs 9.2
c 1
b 0
f 0
cc 4
eloc 8
nc 3
nop 1
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
        $newSubscribers = $this->getNewSubscribers();
132
133
        // Some subscribers may only be used, if the SDK is verified
134
        if ($verified) {
135
            $newSubscribers = array_merge($newSubscribers, [
136
                new \ShopwarePlugins\Connect\Subscribers\BasketWidget(
137
                    $this->pluginBootstrap->getBasketHelper(),
138
                    $this->helper
139
                ),
140
                new Checkout(
141
                    $this->modelManager,
142
                    $this->eventManager,
143
                    $this->connectFactory->getSDK(),
144
                    $this->connectFactory->getBasketHelper(),
145
                    $this->connectFactory->getHelper()
146
                ),
147
                new \ShopwarePlugins\Connect\Subscribers\Dispatches(
148
                    $this->helper,
149
                    $this->pluginBootstrap->Path(),
150
                    $this->container->get('snippets')
151
                ),
152
                new \ShopwarePlugins\Connect\Subscribers\Javascript(),
153
                new \ShopwarePlugins\Connect\Subscribers\Less()
154
            ]);
155
            // These subscribers are used if the api key is not valid
156
        } else {
157
            $newSubscribers = array_merge($newSubscribers, [
158
                new \ShopwarePlugins\Connect\Subscribers\DisableConnectInFrontend(
159
                    $this->pluginBootstrap->Path(), $this->container->get('db')
160
                ),
161
                new \ShopwarePlugins\Connect\Subscribers\TemplateExtension(
162
                    $this->pluginBootstrap->Path(),
163
                    $this->container->get('snippets'),
164
                    $this->SDK,
165
                    $this->helper
166
                ),
167
                new \ShopwarePlugins\Connect\Subscribers\Voucher(
168
                    $this->helper,
169
                    $this->connectFactory->getBasketHelper(),
170
                    $this->container->get('snippets')
171
                ),
172
            ]);
173
        }
174
175
        foreach ($newSubscribers as $newSubscriber) {
176
            $this->eventManager->addSubscriber($newSubscriber);
177
        }
178
179
        $this->modelManager->getEventManager()->addEventListener(
180
            [\Doctrine\ORM\Events::onFlush, \Doctrine\ORM\Events::postFlush],
181
            $this
182
        );
183
    }
184
185
    /**
186
     * @return array
187
     */
188
    private function getNewSubscribers()
189
    {
190
        return [
191
            new \ShopwarePlugins\Connect\Subscribers\Article(
192
                new PDO($this->db->getConnection()),
193
                $this->modelManager,
194
                $this->connectFactory->getConnectExport(),
195
                $this->helper,
196
                $this->config,
197
                $this->connectFactory->getSDK(),
198
                $this->container->get('snippets'),
199
                $this->pluginBootstrap->Path()
200
            ),
201
            new \ShopwarePlugins\Connect\Subscribers\ArticleList(
202
                $this->pluginBootstrap->Path(),
203
                $this->container->get('snippets')
204
            ),
205
            new \ShopwarePlugins\Connect\Subscribers\Category(
206
                $this->container->get('dbal_connection'),
207
                $this->createProductStreamService()
208
            ),
209
            new \ShopwarePlugins\Connect\Subscribers\Connect(
210
                $this->config,
211
                $this->SDK,
212
                $this->container->get('snippets'),
213
                $this->pluginBootstrap->Path()
214
            ),
215
            new ControllerPath(
216
                $this->pluginBootstrap->Path(),
217
                $this->container,
218
                $this->container->get('snippets')
219
            ),
220
            new \ShopwarePlugins\Connect\Subscribers\CronJob(
221
                $this->SDK,
222
                $this->connectFactory->getConnectExport(),
223
                $this->config,
224
                $this->helper
225
            ),
226
            new CustomerGroup(
227
                $this->modelManager,
228
                new Logger(Shopware()->Db())
229
            ),
230
            $this->getLifecycleSubscriber(),
231
            new \ShopwarePlugins\Connect\Subscribers\OrderDocument(),
232
            new \ShopwarePlugins\Connect\Subscribers\PaymentSubscriber(
233
                $this->pluginBootstrap->Path(),
234
                $this->helper
235
            ),
236
            new \ShopwarePlugins\Connect\Subscribers\ProductStreams(
237
                $this->connectFactory->getConnectExport(),
238
                new Config($this->modelManager),
239
                $this->helper,
240
                $this->SDK,
241
                $this->pluginBootstrap->Path(),
242
                $this->container->get('snippets')
243
            ),
244
            new \ShopwarePlugins\Connect\Subscribers\Property(
245
                $this->modelManager,
246
                $this->pluginBootstrap->Path(),
247
                $this->container->get('snippets')
248
            ),
249
            new \ShopwarePlugins\Connect\Subscribers\Search(
250
                $this->modelManager,
251
                $this->pluginBootstrap->Path(),
252
                $this->container->get('snippets')
253
            ),
254
            new \ShopwarePlugins\Connect\Subscribers\ServiceContainer(
255
                $this->modelManager,
256
                $this->db,
257
                $this->container
258
            ),
259
            new \ShopwarePlugins\Connect\Subscribers\Supplier(
260
                $this->pluginBootstrap->Path(),
261
                $this->container->get('snippets'),
262
                $this->container->get('dbal_connection')
263
            ),
264
        ];
265
    }
266
267
    /**
268
     * Generate changes for updated Articles and Details.
269
     * On postFlush all related entities are updated and product can
270
     * be fetched from DB correctly.
271
     *
272
     * @param \Doctrine\ORM\Event\PostFlushEventArgs $eventArgs
273
     */
274
    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...
275
    {
276
        foreach ($this->productUpdates as $entity) {
277
            $this->getLifecycleSubscriber()->handleChange($entity);
278
        }
279
280
        $this->productUpdates = [];
281
    }
282
283
    /**
284
     * @return Lifecycle
285
     */
286
    private function getLifecycleSubscriber()
287
    {
288
        if (!$this->lifecycle) {
289
            $this->lifecycle = new Lifecycle(
290
                $this->modelManager,
291
                $this->config->getConfig('autoUpdateProducts', 1),
292
                $this->helper,
293
                $this->SDK,
294
                $this->config,
295
                $this->connectFactory->getConnectExport()
296
            );
297
        }
298
299
        return $this->lifecycle;
300
    }
301
302
    /**
303
     * Collect updated Articles and Details
304
     * Lifecycle events don't work correctly, because products will be fetched via query builder,
305
     * but related entities like price are not updated yet.
306
     *
307
     * @param \Doctrine\ORM\Event\OnFlushEventArgs $eventArgs
308
     */
309
    public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $eventArgs)
310
    {
311
        /** @var $em ModelManager */
312
        $em  = $eventArgs->getEntityManager();
313
        $uow = $em->getUnitOfWork();
314
315
        // Entity updates
316
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
317
            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...
318
                && !$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...
319
            ) {
320
                continue;
321
            }
322
323
            $this->productUpdates[] = $entity;
324
        }
325
    }
326
327
    /**
328
     * @return ProductStreamService
329
     */
330 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...
331
    {
332
        /** @var ProductStreamAttributeRepository $streamAttrRepository */
333
        $streamAttrRepository = $this->modelManager->getRepository('Shopware\CustomModels\Connect\ProductStreamAttribute');
334
335
        return new ProductStreamService(
336
            new ProductStreamRepository($this->modelManager, $this->container->get('shopware_product_stream.repository')),
337
            $streamAttrRepository,
338
            new Config($this->modelManager),
339
            $this->container->get('shopware_search.product_search'),
340
            $this->container->get('shopware_storefront.context_service')
341
        );
342
    }
343
}
344