Completed
Pull Request — master (#392)
by Christian
03:17
created

SubscriberRegistration::onFlush()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 3
nop 1
dl 0
loc 18
rs 8.8571
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\ConfigFactory;
16
use ShopwarePlugins\Connect\Components\ConnectFactory;
17
use ShopwarePlugins\Connect\Components\Helper;
18
use ShopwarePlugins\Connect\Subscribers\Checkout;
19
use ShopwarePlugins\Connect\Subscribers\Lifecycle;
20
use Symfony\Component\DependencyInjection\Container;
21
22
class SubscriberRegistration
23
{
24
    /**
25
     * @var ModelManager
26
     */
27
    private $modelManager;
28
29
    /**
30
     * @var Config
31
     */
32
    private $config;
33
34
    /**
35
     * @var Enlight_Components_Db_Adapter_Pdo_Mysql
36
     */
37
    private $db;
38
39
    /**
40
     * @TODO: Subscribers should not depend on the Bootstrap class. If you see a possible solution refactor it please.
41
     *
42
     * @var \Shopware_Plugins_Backend_SwagConnect_Bootstrap
43
     */
44
    private $pluginBootstrap;
45
46
    /**
47
     * @var \Enlight_Event_EventManager
48
     */
49
    private $eventManager;
50
51
    /**
52
     * @var SDK
53
     */
54
    private $SDK;
55
56
    /**
57
     * @var ConnectFactory
58
     */
59
    private $connectFactory;
60
61
    /**
62
     * @var Helper
63
     */
64
    private $helper;
65
66
    /**
67
     * This property saves all product updates and will be inserted back later
68
     *
69
     * @var array
70
     */
71
    private $productUpdates = [];
72
73
    /**
74
     * @var Lifecycle
75
     */
76
    private $lifecycle;
77
78
    /**
79
     * @var Container
80
     */
81
    private $container;
82
83
    /**
84
     * @param Config $config
85
     * @param ModelManager $modelManager
86
     * @param Enlight_Components_Db_Adapter_Pdo_Mysql $db
87
     * @param \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap
88
     * @param \Enlight_Event_EventManager $eventManager
89
     * @param SDK $SDK
90
     * @param ConnectFactory $connectFactory
91
     * @param Helper $helper
92
     * @param Container $container
93
     */
94
    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...
95
        Config $config,
96
        ModelManager $modelManager,
97
        Enlight_Components_Db_Adapter_Pdo_Mysql $db,
98
        \Shopware_Plugins_Backend_SwagConnect_Bootstrap $pluginBootstrap,
99
        \Enlight_Event_EventManager $eventManager,
100
        SDK $SDK,
101
        ConnectFactory $connectFactory,
102
        Helper $helper,
103
        Container $container
104
    ) {
105
        $this->config = $config;
106
        $this->modelManager = $modelManager;
107
        $this->db = $db;
108
        $this->pluginBootstrap = $pluginBootstrap;
109
        $this->eventManager = $eventManager;
110
        $this->SDK = $SDK;
111
        $this->connectFactory = $connectFactory;
112
        $this->helper = $helper;
113
        $this->container = $container;
114
    }
115
116
    public function registerSubscribers()
117
    {
118
        try {
119
            $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...
120
        } catch (\Exception $e) {
121
            // if the config table is not available, just assume, that the update
122
            // still needs to be installed
123
            $verified = false;
124
        }
125
126
        $subscribers = $this->getDefaultSubscribers();
127
128
        // Some subscribers may only be used, if the SDK is verified
129
        if ($verified) {
130
            $subscribers = array_merge($subscribers, $this->getSubscribersForVerifiedKeys());
131
            // These subscribers are used if the api key is not valid
132
        } else {
133
            $subscribers = array_merge($subscribers, $this->getSubscribersForUnverifiedKeys());
134
        }
135
136
        /** @var $subscriber \ShopwarePlugins\Connect\Subscribers\BaseSubscriber */
137
        foreach ($subscribers as $subscriber) {
138
            $subscriber->setBootstrap($this->pluginBootstrap);
139
            $this->eventManager->registerSubscriber($subscriber);
140
        }
141
142
        $this->modelManager->getEventManager()->addEventListener(
143
            [\Doctrine\ORM\Events::onFlush, \Doctrine\ORM\Events::postFlush],
144
            $this
145
        );
146
    }
147
148
    /**
149
     * Default subscribers can safely be used, even if the api key wasn't verified, yet
150
     *
151
     * @return array
152
     */
153
    private function getDefaultSubscribers()
154
    {
155
        return [
156
            new \ShopwarePlugins\Connect\Subscribers\OrderDocument(),
157
            new \ShopwarePlugins\Connect\Subscribers\ControllerPath(),
158
            new \ShopwarePlugins\Connect\Subscribers\CustomerGroup(),
159
            new \ShopwarePlugins\Connect\Subscribers\CronJob(
160
                $this->SDK,
161
                $this->connectFactory->getConnectExport()
162
            ),
163
            new \ShopwarePlugins\Connect\Subscribers\ArticleList(),
164
            new \ShopwarePlugins\Connect\Subscribers\Article(
165
                new PDO($this->db->getConnection()),
166
                $this->modelManager,
167
                $this->connectFactory->getConnectExport(),
168
                $this->helper,
169
                $this->config
170
            ),
171
            new \ShopwarePlugins\Connect\Subscribers\Category(
172
                $this->modelManager
173
            ),
174
            new \ShopwarePlugins\Connect\Subscribers\Connect(),
175
            new \ShopwarePlugins\Connect\Subscribers\Payment(),
176
            new \ShopwarePlugins\Connect\Subscribers\ServiceContainer(
177
                $this->modelManager,
178
                $this->db,
179
                $this->container,
180
                $this->config
181
            ),
182
            new \ShopwarePlugins\Connect\Subscribers\Supplier(),
183
            new \ShopwarePlugins\Connect\Subscribers\ProductStreams(
184
                $this->connectFactory->getConnectExport(),
185
                ConfigFactory::getConfigInstance(),
186
                $this->helper
187
            ),
188
            new \ShopwarePlugins\Connect\Subscribers\Property(
189
                $this->modelManager
190
            ),
191
            new \ShopwarePlugins\Connect\Subscribers\Search(
192
                $this->modelManager
193
            ),
194
        ];
195
    }
196
197
    /**
198
     * @return array
199
     */
200
    private function getSubscribersForUnverifiedKeys()
201
    {
202
        return [
203
            new \ShopwarePlugins\Connect\Subscribers\DisableConnectInFrontend(),
204
            $this->getLifecycleSubscriber()
205
        ];
206
    }
207
208
    /**
209
     * These subscribers will only be used, once the user has verified his api key
210
     * This will prevent the users from having shopware Connect extensions in their frontend
211
     * even if they cannot use shopware Connect due to the missing / wrong api key
212
     *
213
     * @return array
214
     */
215
    private function getSubscribersForVerifiedKeys()
216
    {
217
        $subscribers = [
218
            new \ShopwarePlugins\Connect\Subscribers\TemplateExtension(),
219
            $this->createCheckoutSubscriber(),
220
            new \ShopwarePlugins\Connect\Subscribers\Voucher(),
221
            new \ShopwarePlugins\Connect\Subscribers\BasketWidget(),
222
            new \ShopwarePlugins\Connect\Subscribers\Dispatches(),
223
            new \ShopwarePlugins\Connect\Subscribers\Javascript(),
224
            new \ShopwarePlugins\Connect\Subscribers\Less(),
225
            $this->getLifecycleSubscriber()
226
227
        ];
228
229
        return $subscribers;
230
    }
231
232
    /**
233
     * Creates checkout subscriber
234
     *
235
     * @return Checkout
236
     */
237
    private function createCheckoutSubscriber()
238
    {
239
        $checkoutSubscriber = new Checkout(
240
            $this->modelManager,
241
            $this->eventManager
242
        );
243
        foreach ($checkoutSubscriber->getListeners() as $listener) {
244
            if ($listener->getName() === 'Enlight_Controller_Action_PostDispatch_Frontend_Checkout') {
245
                $listener->setPosition(-1);
246
            }
247
        }
248
249
        return $checkoutSubscriber;
250
    }
251
252
    /**
253
     * Generate changes for updated Articles and Details.
254
     * On postFlush all related entities are updated and product can
255
     * be fetched from DB correctly.
256
     *
257
     * @param \Doctrine\ORM\Event\PostFlushEventArgs $eventArgs
258
     */
259
    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...
260
    {
261
        $updates = $this->expandConfigSetsToProducts($this->productUpdates);
262
263
        foreach ($updates as $entity) {
264
            $this->getLifecycleSubscriber()->handleChange($entity);
265
        }
266
267
        $this->productUpdates = [];
268
    }
269
270
    /**
271
     * @param array $productUpdates
272
     * @return array
273
     */
274
    private function expandConfigSetsToProducts($productUpdates)
275
    {
276
        $updates = [];
277
        foreach ($productUpdates as $entity) {
278
            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...
279
                foreach ($entity->getArticles() as $article) {
280
                    $updates[] = $article;
281
                }
282
            } else {
283
                $updates[] = $entity;
284
            }
285
        }
286
287
        return $updates;
288
    }
289
290
    /**
291
     * @return Lifecycle
292
     */
293
    private function getLifecycleSubscriber()
294
    {
295
        if (!$this->lifecycle) {
296
            $this->lifecycle = new Lifecycle(
297
                $this->modelManager,
298
                $this->config->getConfig('autoUpdateProducts', 1)
299
            );
300
        }
301
302
        return $this->lifecycle;
303
    }
304
305
    /**
306
     * Collect updated Articles and Details
307
     * Lifecycle events don't work correctly, because products will be fetched via query builder,
308
     * but related entities like price are not updated yet.
309
     *
310
     * @param \Doctrine\ORM\Event\OnFlushEventArgs $eventArgs
311
     */
312
    public function onFlush(\Doctrine\ORM\Event\OnFlushEventArgs $eventArgs)
313
    {
314
        /** @var $em ModelManager */
315
        $em = $eventArgs->getEntityManager();
316
        $uow = $em->getUnitOfWork();
317
318
        // Entity updates
319
        foreach ($uow->getScheduledEntityUpdates() as $entity) {
320
            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...
321
                && !$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...
322
                && !$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...
323
            ) {
324
                continue;
325
            }
326
327
            $this->productUpdates[] = $entity;
328
        }
329
    }
330
}
331