Completed
Pull Request — master (#394)
by Jonas
02:59
created

SubscriberRegistration::onFlush()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 3
nop 1
dl 0
loc 17
rs 9.2
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
        foreach ($this->productUpdates as $entity) {
236
            $this->getLifecycleSubscriber()->handleChange($entity);
237
        }
238
239
        $this->productUpdates = [];
240
    }
241
242
    /**
243
     * @return Lifecycle
244
     */
245
    private function getLifecycleSubscriber()
246
    {
247
        if (!$this->lifecycle) {
248
            $this->lifecycle = new Lifecycle(
249
                $this->modelManager,
250
                $this->helper,
251
                $this->SDK,
252
                $this->config,
253
                $this->connectFactory->getConnectExport()
254
            );
255
        }
256
257
        return $this->lifecycle;
258
    }
259
260
    /**
261
     * Collect updated Articles and Details
262
     * Lifecycle events don't work correctly, because products will be fetched via query builder,
263
     * but related entities like price are not updated yet.
264
     *
265
     * @param \Doctrine\ORM\Event\OnFlushEventArgs $eventArgs
266
     */
267
    public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $eventArgs)
268
    {
269
        /** @var $em ModelManager */
270
        $em  = $eventArgs->getEntityManager();
271
        $uow = $em->getUnitOfWork();
272
273
        // Entity updates
274
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
275
            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...
276
                && !$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...
277
            ) {
278
                continue;
279
            }
280
281
            $this->productUpdates[] = $entity;
282
        }
283
    }
284
285
    /**
286
     * @return ProductStreamService
287
     */
288 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...
289
    {
290
        /** @var ProductStreamAttributeRepository $streamAttrRepository */
291
        $streamAttrRepository = $this->modelManager->getRepository('Shopware\CustomModels\Connect\ProductStreamAttribute');
292
293
        return new ProductStreamService(
294
            new ProductStreamRepository($this->modelManager, $this->container->get('shopware_product_stream.repository')),
295
            $streamAttrRepository,
296
            $this->config,
297
            $this->container->get('shopware_search.product_search'),
298
            $this->container->get('shopware_storefront.context_service')
299
        );
300
    }
301
302
    /**
303
     * @return array
304
     */
305
    private function getVerifiedSubscribers()
306
    {
307
        return [
308
            new BasketWidget(
309
                $this->pluginBootstrap->getBasketHelper(),
310
                $this->helper
311
            ),
312
            new Checkout(
313
                $this->modelManager,
314
                $this->eventManager,
315
                $this->connectFactory->getSDK(),
316
                $this->connectFactory->getBasketHelper(),
317
                $this->connectFactory->getHelper()
318
            ),
319
            new Dispatches($this->helper),
320
            new Javascript(),
321
            new TemplateExtension(
322
                $this->SDK,
323
                $this->helper
324
            ),
325
            new Voucher(
326
                $this->helper,
327
                $this->connectFactory->getBasketHelper(),
328
                $this->container->get('snippets')
329
            ),
330
            new Less()
331
        ];
332
    }
333
334
    /**
335
     * @return array
336
     */
337
    private function getNotVerifiedSubscribers()
338
    {
339
        return [
340
            new DisableConnectInFrontend(
341
                $this->container->get('db')
342
            )
343
        ];
344
    }
345
}
346