Completed
Pull Request — master (#358)
by Stefan
03:09
created

getSubscribersForVerifiedKeys()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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