Article::modifyConnectArticle()   C
last analyzed

Complexity

Conditions 11
Paths 9

Size

Total Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
nc 9
nop 1
dl 0
loc 62
rs 6.6824
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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\Subscribers;
9
10
use Shopware\Connect\SDK;
11
use Enlight\Event\SubscriberInterface;
12
use Shopware\CustomModels\Connect\Attribute;
13
use ShopwarePlugins\Connect\Components\Config;
14
use Shopware\Connect\Struct\Change\FromShop\MakeMainVariant;
15
use Shopware\Models\Customer\Group;
16
use Shopware\Connect\Gateway;
17
use Shopware\Components\Model\ModelManager;
18
use ShopwarePlugins\Connect\Components\ConnectExport;
19
use Shopware\Models\Article\Article as ArticleModel;
20
use ShopwarePlugins\Connect\Components\Helper;
21
use Shopware\Models\Article\Detail;
22
use Shopware\Models\Attribute\CustomerGroup as CustomerGroupAttribute;
23
use ShopwarePlugins\Connect\Services\RemoteShopService;
24
25
/**
26
 * Class Article
27
 * @package ShopwarePlugins\Connect\Subscribers
28
 */
29
class Article implements SubscriberInterface
30
{
31
    /**
32
     * @var \Shopware\Connect\Gateway\PDO
33
     */
34
    private $connectGateway;
35
36
    /**
37
     * @var \Shopware\Components\Model\ModelManager
38
     */
39
    private $modelManager;
40
41
    /**
42
     * @var \Shopware\Models\Customer\Group
43
     */
44
    private $customerGroupRepository;
45
46
    /**
47
     * @var \Shopware\Models\Article\Detail
48
     */
49
    private $detailRepository;
50
51
    /**
52
     * @var \ShopwarePlugins\Connect\Components\ConnectExport
53
     */
54
    private $connectExport;
55
56
    /**
57
     * @var Helper
58
     */
59
    private $helper;
60
61
    /**
62
     * @var Config
63
     */
64
    private $config;
65
66
    /**
67
     * @var SDK
68
     */
69
    private $sdk;
70
71
    /**
72
     * @param Gateway $connectGateway
73
     * @param ModelManager $modelManager
74
     * @param ConnectExport $connectExport
75
     * @param Helper $helper
76
     * @param Config $config
77
     * @param SDK $sdk
78
     */
79
    public function __construct(
80
        Gateway $connectGateway,
81
        ModelManager $modelManager,
82
        ConnectExport $connectExport,
83
        Helper $helper,
84
        Config $config,
85
        SDK $sdk
86
    ) {
87
        $this->connectGateway = $connectGateway;
0 ignored issues
show
Documentation Bug introduced by
$connectGateway is of type object<Shopware\Connect\Gateway>, but the property $connectGateway was declared to be of type object<Shopware\Connect\Gateway\PDO>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
88
        $this->modelManager = $modelManager;
89
        $this->connectExport = $connectExport;
90
        $this->helper = $helper;
91
        $this->config = $config;
92
        $this->sdk = $sdk;
93
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98
    public static function getSubscribedEvents()
99
    {
100
        return [
101
            'Shopware_Controllers_Backend_Article::preparePricesAssociatedData::after' => 'enforceConnectPriceWhenSaving',
102
            'Enlight_Controller_Action_PostDispatch_Backend_Article' => 'extendBackendArticle',
103
            'Enlight_Controller_Action_PreDispatch_Backend_Article' => 'preBackendArticle',
104
            'Enlight_Controller_Action_PostDispatch_Frontend_Detail' => 'modifyConnectArticle',
105
            'Enlight_Controller_Action_PreDispatch_Frontend_Detail' => 'extendFrontendArticle',
106
            'Shopware_Modules_Basket_AddArticle_Start' => 'checkSupplierPluginAvailability'
107
        ];
108
    }
109
110
    /**
111
     * @param \Enlight_Event_EventArgs $args
112
     * @throws \Exception
113
     * @return bool|void
114
     */
115
    public function checkSupplierPluginAvailability(\Enlight_Event_EventArgs $args)
116
    {
117
        $articleDetail = $this->helper->getDetailByNumber($args->getId());
118
        if (!$articleDetail instanceof 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...
119
            return;
120
        }
121
122
        $articleDetailId = $articleDetail->getId();
123
124
        if (!$this->helper->isRemoteArticleDetail($articleDetailId)) {
125
            return;
126
        }
127
128
        $shopProductId = $this->helper->getShopProductId($articleDetailId);
129
        $shopId = $shopProductId->shopId;
130
131
        /**
132
         * @var RemoteShopService
133
         * @todo: refactor when using 5.2 plugin base.
134
         */
135
        $remoteShopService = Shopware()->Container()->get('swagconnect.remote_shop_service');
136
137
        if ($remoteShopService->isPingRemoteShopSuccessful($shopId)) {
138
            return;
139
        }
140
141
        $this->createBasketInfoMessagesOnFailingRemoteShopPing();
142
143
        // Prevent adding article to basket
144
        return false;
145
    }
146
147
    private function createBasketInfoMessagesOnFailingRemoteShopPing()
148
    {
149
        $infoMessage = Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
150
            'connect/basket/addArticleFailedInfoMessage',
151
            'The marketplace product could not be added to the basket because it is not available.'
152
        );
153
154
        Shopware()->Template()
155
            ->assign('basketInfoMessage', $infoMessage)
156
            ->assign('sBasketInfo', $infoMessage);
157
    }
158
159
    /**
160
     * @return \Shopware\Models\Article\Detail
161
     */
162
    public function getDetailRepository()
163
    {
164
        if (!$this->detailRepository) {
165
            $this->detailRepository = $this->modelManager->getRepository(Detail::class);
166
        }
167
168
        return $this->detailRepository;
169
    }
170
171
    /**
172
     * @return \Shopware\Components\Model\ModelRepository|Group
173
     */
174
    public function getCustomerGroupRepository()
175
    {
176
        if (!$this->customerGroupRepository) {
177
            $this->customerGroupRepository = $this->modelManager->getRepository(Group::class);
178
        }
179
180
        return $this->customerGroupRepository;
181
    }
182
183
    /**
184
     * @param \Enlight_Event_EventArgs $args
185
     */
186
    public function preBackendArticle(\Enlight_Event_EventArgs $args)
187
    {
188
        /** @var $subject \Enlight_Controller_Action */
189
        $subject = $args->getSubject();
190
        $request = $subject->Request();
191
192
        switch ($request->getActionName()) {
193
            case 'saveDetail':
194
                if ($request->getParam('standard')) {
195
                    $this->generateMainVariantChange($request->getParam('id'));
196
                }
197
                break;
198
            case 'createConfiguratorVariants':
199
                if (!$articleId = $request->getParam('articleId')) {
200
                    return;
201
                }
202
203
                $this->deleteVariants($articleId);
204
                break;
205
        }
206
    }
207
208
    /**
209
     * @event Enlight_Controller_Action_PostDispatch_Backend_Article
210
     * @param \Enlight_Event_EventArgs $args
211
     */
212
    public function extendBackendArticle(\Enlight_Event_EventArgs $args)
213
    {
214
        /** @var $subject \Enlight_Controller_Action */
215
        $subject = $args->getSubject();
216
        $request = $subject->Request();
217
218
        switch ($request->getActionName()) {
219
            case 'index':
220
                $subject->View()->extendsTemplate(
221
                    'backend/article/connect.js'
222
                );
223
                break;
224
            case 'load':
225
                $subject->View()->extendsTemplate(
226
                    'backend/article/model/attribute_connect.js'
227
                );
228
                $subject->View()->assign('disableConnectPrice', 'true');
229
                $subject->View()->extendsTemplate(
230
                    'backend/article/view/detail/connect_tab.js'
231
                );
232
                $subject->View()->extendsTemplate(
233
                    'backend/article/view/detail/prices_connect.js'
234
                );
235
                $subject->View()->extendsTemplate(
236
                    'backend/article/controller/detail_connect.js'
237
                );
238
                $subject->View()->extendsTemplate(
239
                    'backend/article/view/detail/connect_properties.js'
240
                );
241
                break;
242
            case 'setPropertyList':
243
                // property values are saved in different ajax call then
244
                // property group and this will generate wrong Connect changes.
245
                // after the property values are saved, the temporary property group is no needed
246
                // and it will generate right Connect changes
247
                $articleId = $request->getParam('articleId', null);
248
249
                /** @var ArticleModel $article */
250
                $article = $this->modelManager->find(ArticleModel::class, $articleId);
251
252
                if (!$article) {
253
                    return;
254
                }
255
256
                if (!$article->getPropertyGroup()) {
257
                    return;
258
                }
259
260
                // Check if entity is a connect product
261
                $attribute = $this->helper->getConnectAttributeByModel($article);
262
                if (!$attribute) {
263
                    return;
264
                }
265
266
                // if article is not exported to Connect
267
                // don't need to generate changes
268
                if (!$this->helper->isProductExported($attribute) || !empty($attribute->getShopId())) {
269
                    return;
270
                }
271
272
                if (!SDK::isPriceTypeValid($this->sdk->getPriceType())) {
273
                    return;
274
                }
275
276
                $detail = $article->getMainDetail();
277
278
                if ($detail->getAttribute()->getConnectPropertyGroup()) {
279
                    $detail->getAttribute()->setConnectPropertyGroup(null);
280
                    $this->modelManager->persist($detail);
281
                    $this->modelManager->flush();
282
                }
283
284
                $autoUpdateProducts = $this->config->getConfig('autoUpdateProducts');
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $autoUpdateProducts is correct as $this->config->getConfig('autoUpdateProducts') (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...
285
                if ($autoUpdateProducts == Config::UPDATE_CRON_JOB) {
286
                    $this->modelManager->getConnection()->update(
287
                        's_plugin_connect_items',
288
                        ['cron_update' => 1],
289
                        ['article_id' => $article->getId()]
290
                    );
291
                } else {
292
                    $sourceIds = $this->modelManager->getConnection()->executeQuery(
293
                        'SELECT source_id FROM s_plugin_connect_items WHERE article_id = ?',
294
                        [$article->getId()]
295
                    )->fetchAll(\PDO::FETCH_COLUMN);
296
                    $this->connectExport->export($sourceIds);
297
                }
298
                break;
299
            case 'createConfiguratorVariants':
300
                // main detail should be updated as well, because shopware won't call lifecycle event
301
                // even postUpdate of Detail. By this way Connect will generate change for main variant,
302
                // otherwise $product->variant property is an empty array
303
                // if main detail is not changed, Connect SDK won't generate change for it.
304
                // ticket CON-3747
305
                if (!$articleId = $request->getParam('articleId')) {
306
                    return;
307
                }
308
309
                $this->regenerateChangesForArticle($articleId);
310
                break;
311
            case 'getPropertyList':
312
                $subject->View()->data = $this->addConnectFlagToProperties(
313
                    $subject->View()->data
314
                );
315
                break;
316
            case 'deleteAllVariants':
317
                if ($articleId = $request->getParam('articleId')) {
318
                    /** @var ArticleModel $article */
319
                    $article = $this->modelManager->find(ArticleModel::class, (int) $articleId);
320
                    if (!$article) {
321
                        return;
322
                    }
323
324
                    $this->deleteVariants($articleId);
325
                }
326
                break;
327
            default:
328
                break;
329
        }
330
    }
331
332
    /**
333
     * @param int $articleId
334
     */
335
    public function regenerateChangesForArticle($articleId)
336
    {
337
        $autoUpdateProducts = $this->config->getConfig('autoUpdateProducts', Config::UPDATE_AUTO);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $autoUpdateProducts is correct as $this->config->getConfig...ts\Config::UPDATE_AUTO) (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...
338
        if ($autoUpdateProducts == Config::UPDATE_MANUAL) {
339
            return;
340
        }
341
342
        /** @var \Shopware\Models\Article\Article $article */
343
        $article = $this->modelManager->getRepository(ArticleModel::class)->find((int) $articleId);
344
        if (!$article) {
345
            return;
346
        }
347
348
        $attribute = $this->helper->getConnectAttributeByModel($article);
349
        if (!$attribute) {
350
            return;
351
        }
352
353
        // Check if entity is a connect product
354
        if (!$this->helper->isProductExported($attribute)) {
355
            return;
356
        }
357
358
        if ($autoUpdateProducts == Config::UPDATE_CRON_JOB) {
359
            $this->connectExport->markArticleForCronUpdate($articleId);
360
361
            return;
362
        }
363
364
        $this->connectExport->export($this->helper->getArticleSourceIds([$articleId]));
365
    }
366
367
    /**
368
     * Delete all variants of given product except main one
369
     *
370
     * @param int $articleId
371
     */
372
    private function deleteVariants($articleId)
373
    {
374
        $autoUpdateProducts = $this->config->getConfig('autoUpdateProducts', Config::UPDATE_AUTO);
0 ignored issues
show
Bug introduced by
Are you sure the assignment to $autoUpdateProducts is correct as $this->config->getConfig...ts\Config::UPDATE_AUTO) (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...
375
        if ($autoUpdateProducts == Config::UPDATE_MANUAL) {
376
            return;
377
        }
378
379
        /** @var \Shopware\Models\Article\Article $article */
380
        $article = $this->modelManager->getRepository(ArticleModel::class)->find((int) $articleId);
381
        if (!$article) {
382
            return;
383
        }
384
385
        $connectAttribute = $this->helper->getConnectAttributeByModel($article);
386
        if (!$connectAttribute) {
387
            return;
388
        }
389
390
        // Check if entity is a connect product
391
        if (!$this->helper->isProductExported($connectAttribute)) {
392
            return;
393
        }
394
395
        $mainVariantSourceId = $connectAttribute->getSourceId();
396
        $sourceIds = array_filter(
397
            $this->helper->getArticleSourceIds([$article->getId()]),
398
            function ($sourceId) use ($mainVariantSourceId) {
399
                return $sourceId != $mainVariantSourceId;
400
            }
401
        );
402
403
        foreach ($sourceIds as $sourceId) {
404
            $this->sdk->recordDelete($sourceId);
405
        }
406
407
        $this->connectExport->updateConnectItemsStatus($sourceIds, Attribute::STATUS_DELETE);
408
    }
409
410
    public function addConnectFlagToProperties($data)
411
    {
412
        $groups = [];
413
        foreach ($data as $group) {
414
            $options = [];
415
            foreach ($group['value'] as $value) {
416
                $element = $value;
417
                $optionId = $value['id'];
418
                $valueModel = $this->modelManager->getRepository('Shopware\Models\Property\Value')->find($optionId);
419
420
                $attribute = null;
421
                if ($valueModel) {
422
                    $attribute = $valueModel->getAttribute();
423
                }
424
425
                if ($attribute && $attribute->getConnectIsRemote()) {
426
                    $element['connect'] = true;
427
                } else {
428
                    $element['connect'] = false;
429
                }
430
                $options[] = $element;
431
            }
432
433
            $group['value'] = $options;
434
            $groups[] = $group;
435
        }
436
437
        return $groups;
438
    }
439
440
    /**
441
     * @param $detailId
442
     */
443
    public function generateMainVariantChange($detailId)
444
    {
445
        $detail = $this->getDetailRepository()->findOneBy(['id' => $detailId]);
446
447
        if (!$detail 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...
448
            return;
449
        }
450
451
        //if it is already main variant dont generate MakeMainVariant change
452
        if ($detail->getKind() == 1) {
453
            return;
454
        }
455
456
        $attribute = $this->helper->getConnectAttributeByModel($detail);
457
458
        if (!$attribute) {
459
            return;
460
        }
461
        // Check if entity is a connect product
462
        if (!$this->helper->isProductExported($attribute)) {
463
            return;
464
        }
465
466
        if (!SDK::isPriceTypeValid($this->sdk->getPriceType())) {
467
            return;
468
        }
469
470
        $groupId = $attribute->getGroupId() ? $attribute->getGroupId() : $attribute->getArticleId();
471
472
        $mainVariant = new MakeMainVariant([
473
            'sourceId' => $attribute->getSourceId(),
474
            'groupId' => $groupId
475
        ]);
476
477
        try {
478
            $this->sdk->makeMainVariant($mainVariant);
479
        } catch (\Exception $e) {
480
            // if sn is not available, proceed without exception
481
        }
482
    }
483
484
    /**
485
     * When saving prices make sure, that the connectPrice is stored in net
486
     *
487
     * @param \Enlight_Hook_HookArgs $args
488
     */
489
    public function enforceConnectPriceWhenSaving(\Enlight_Hook_HookArgs $args)
490
    {
491
        /** @var array $prices */
492
        $prices = $args->getReturn();
493
494
        $connectCustomerGroup = $this->getConnectCustomerGroup();
495
        if (!$connectCustomerGroup) {
496
            return;
497
        }
498
        $connectCustomerGroupKey = $connectCustomerGroup->getKey();
499
        $defaultPrices = [];
500
        foreach ($prices as $key => $priceData) {
501
            if ($priceData['customerGroupKey'] == $connectCustomerGroupKey) {
502
                return;
503
            }
504
            if ($priceData['customerGroupKey'] == 'EK') {
505
                $defaultPrices[] = $priceData;
506
            }
507
        }
508
509
        foreach ($defaultPrices as $price) {
510
            $prices[] = [
511
                'from' => $price['from'],
512
                'to' => $price['to'],
513
                'price' => $price['price'],
514
                'pseudoPrice' => $price['pseudoPrice'],
515
                'basePrice' => $price['basePrice'],
516
                'percent' => $price['percent'],
517
                'customerGroup' => $connectCustomerGroup,
518
                'article' => $price['article'],
519
                'articleDetail' => $price['articleDetail'],
520
            ];
521
        }
522
523
        $args->setReturn($prices);
524
    }
525
526
    /**
527
     * @return \Shopware\Models\Customer\Group|null
528
     */
529 View Code Duplication
    public function getConnectCustomerGroup()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
530
    {
531
        $repo = $this->modelManager->getRepository(CustomerGroupAttribute::class);
532
        /** @var \Shopware\Models\Attribute\CustomerGroup $model */
533
        $model = $repo->findOneBy(['connectGroup' => true]);
534
535
        $customerGroup = null;
0 ignored issues
show
Unused Code introduced by
$customerGroup is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
536
        if ($model && $model->getCustomerGroup()) {
537
            return $model->getCustomerGroup();
538
        }
539
540
        return null;
541
    }
542
543
    /**
544
     * Load article detail
545
     *
546
     * @param \Enlight_Event_EventArgs $args
547
     */
548
    public function extendFrontendArticle(\Enlight_Event_EventArgs $args)
549
    {
550
        /** @var \Enlight_Controller_Request_RequestHttp $request */
551
        $request = $args->getSubject()->Request();
552
        if ($request->getActionName() != 'index') {
553
            return;
554
        }
555
556
        $detailId = (int) $request->sArticleDetail;
557
        if ($detailId === 0) {
558
            return;
559
        }
560
561
        /** @var \Shopware\Models\Article\Detail $detailModel */
562
        $detailModel = $this->modelManager->getRepository(Detail::class)->find($detailId);
563
        if (!$detailModel) {
564
            return;
565
        }
566
567
        $params = [];
568
        /** @var \Shopware\Models\Article\Configurator\Option $option */
569
        foreach ($detailModel->getConfiguratorOptions() as $option) {
570
            $groupId = $option->getGroup()->getId();
571
            $params[$groupId] = $option->getId();
572
        }
573
        $request->setPost('group', $params);
574
    }
575
576
    /**
577
     * Should be possible to buy connect products
578
     * when they're not in stock.
579
     * Depends on remote shop configuration.
580
     *
581
     * @param \Enlight_Event_EventArgs $args
582
     */
583
    public function modifyConnectArticle(\Enlight_Event_EventArgs $args)
584
    {
585
        /** @var \Enlight_Controller_Request_RequestHttp $request */
586
        $request = $args->getSubject()->Request();
587
588
        if ($request->getActionName() != 'index') {
589
            return;
590
        }
591
        $subject = $args->getSubject();
592
        $article = $subject->View()->getAssign('sArticle');
593
        if (!$article) {
594
            return;
595
        }
596
597
        // when article stock is greater than 0
598
        // we don't need to modify it.
599
        if ($article['instock'] > 0) {
600
            return;
601
        }
602
603
        $articleId = $article['articleID'];
604
        $remoteShopId = $this->getRemoteShopId($articleId);
605
        if (!$remoteShopId) {
606
            // article is not imported via Connect
607
            return;
608
        }
609
610
        /** @var \Shopware\Models\Article\Article $articleModel */
611
        $articleModel = $this->modelManager->getRepository(ArticleModel::class)->find($articleId);
612
        if (!$articleModel) {
613
            return;
614
        }
615
616
        $shopConfiguration = $this->connectGateway->getShopConfiguration($remoteShopId);
0 ignored issues
show
Documentation introduced by
$remoteShopId is of type boolean|integer, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
617
        if ($shopConfiguration->sellNotInStock && !$articleModel->getLastStock()) {
618
            // if selNotInStock is = true and article getLastStock = false
619
            // we don't need to modify it
620
            return;
621
        }
622
623
        if (!$shopConfiguration->sellNotInStock && $articleModel->getLastStock()) {
624
            // if sellNotInStock is = false and article getLastStock = true
625
            // we don't need to modify it
626
            return;
627
        }
628
629
        // sellNotInStock is opposite on articleLastStock
630
        // when it's true, lastStock must be false
631
        $articleModel->setLastStock(!$shopConfiguration->sellNotInStock);
632
        $this->modelManager->persist($articleModel);
633
        $this->modelManager->flush();
634
635
        // modify assigned article
636
        if ($shopConfiguration->sellNotInStock) {
637
            $article['laststock'] = false;
638
            $article['instock'] = 100;
639
            $article['isAvailable'] = true;
640
        } else {
641
            $article['laststock'] = true;
642
        }
643
        $subject->View()->assign('sArticle', $article);
644
    }
645
646
    /**
647
     * Not using the default helper-methods here, in order to keep this small and without any dependencies
648
     * to the SDK
649
     *
650
     * @param $articleId
651
     * @return bool|int
652
     */
653
    private function getRemoteShopId($articleId)
654
    {
655
        return $this->modelManager->getConnection()->fetchColumn(
656
            'SELECT shop_id FROM s_plugin_connect_items WHERE article_id = ? AND shop_id IS NOT NULL',
657
            [$articleId]
658
        );
659
    }
660
}
661