Completed
Pull Request — master (#358)
by Stefan
02:49
created

SubscriberRegistration::postFlush()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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