Completed
Pull Request — master (#392)
by Christian
03:39
created

SubscriberRegistration::getLifecycleSubscriber()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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