Completed
Pull Request — master (#358)
by Stefan
03:07
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 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
            ),
221
            new Supplier($this->container->get('dbal_connection'))
222
        ];
223
    }
224
225
    /**
226
     * Generate changes for updated Articles and Details.
227
     * On postFlush all related entities are updated and product can
228
     * be fetched from DB correctly.
229
     *
230
     * @param \Doctrine\ORM\Event\PostFlushEventArgs $eventArgs
231
     */
232
    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...
233
    {
234
        foreach ($this->productUpdates as $entity) {
235
            $this->getLifecycleSubscriber()->handleChange($entity);
236
        }
237
238
        $this->productUpdates = [];
239
    }
240
241
    /**
242
     * @return Lifecycle
243
     */
244
    private function getLifecycleSubscriber()
245
    {
246
        if (!$this->lifecycle) {
247
            $this->lifecycle = new Lifecycle(
248
                $this->modelManager,
249
                $this->helper,
250
                $this->SDK,
251
                $this->config,
252
                $this->connectFactory->getConnectExport()
253
            );
254
        }
255
256
        return $this->lifecycle;
257
    }
258
259
    /**
260
     * Collect updated Articles and Details
261
     * Lifecycle events don't work correctly, because products will be fetched via query builder,
262
     * but related entities like price are not updated yet.
263
     *
264
     * @param \Doctrine\ORM\Event\OnFlushEventArgs $eventArgs
265
     */
266
    public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $eventArgs)
267
    {
268
        /** @var $em ModelManager */
269
        $em  = $eventArgs->getEntityManager();
270
        $uow = $em->getUnitOfWork();
271
272
        // Entity updates
273
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
274
            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...
275
                && !$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...
276
            ) {
277
                continue;
278
            }
279
280
            $this->productUpdates[] = $entity;
281
        }
282
    }
283
284
    /**
285
     * @return ProductStreamService
286
     */
287
    private function createProductStreamService()
288
    {
289
        /** @var ProductStreamAttributeRepository $streamAttrRepository */
290
        $streamAttrRepository = $this->modelManager->getRepository('Shopware\CustomModels\Connect\ProductStreamAttribute');
291
292
        return new ProductStreamService(
293
            new ProductStreamRepository($this->modelManager, $this->container->get('shopware_product_stream.repository')),
294
            $streamAttrRepository,
295
            $this->config,
296
            $this->container->get('shopware_search.product_search'),
297
            $this->container->get('shopware_storefront.context_service')
298
        );
299
    }
300
301
    /**
302
     * @return array
303
     */
304
    private function getVerifiedSubscribers()
305
    {
306
        return [
307
            new BasketWidget(
308
                $this->pluginBootstrap->getBasketHelper(),
309
                $this->helper
310
            ),
311
            new Checkout(
312
                $this->modelManager,
313
                $this->eventManager,
314
                $this->connectFactory->getSDK(),
315
                $this->connectFactory->getBasketHelper(),
316
                $this->connectFactory->getHelper()
317
            ),
318
            new Dispatches($this->helper),
319
            new Javascript(),
320
            new TemplateExtension(
321
                $this->SDK,
322
                $this->helper
323
            ),
324
            new Voucher(
325
                $this->helper,
326
                $this->connectFactory->getBasketHelper(),
327
                $this->container->get('snippets')
328
            ),
329
            new Less()
330
        ];
331
    }
332
333
    /**
334
     * @return array
335
     */
336
    private function getNotVerifiedSubscribers()
337
    {
338
        return [
339
            new DisableConnectInFrontend(
340
                $this->container->get('db')
341
            )
342
        ];
343
    }
344
}
345