Completed
Pull Request — master (#392)
by Jonas
03:55
created

expandConfigSetsToProducts()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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