Completed
Push — master ( 3474fd...81362a )
by Daniel
13s
created

SubscriberRegistration::getLifecycleSubscriber()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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