Completed
Push — master ( 512122...851336 )
by Tobias
18s
created

Article::pingRemoteShop()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
nc 2
nop 1
dl 0
loc 13
rs 9.4285
c 1
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\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 View Code Duplication
    public function __construct(
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...
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
     * @return bool|void
113
     * @throws \Exception
114
     */
115
    public function checkSupplierPluginAvailability(\Enlight_Event_EventArgs $args)
116
    {
117
        $articleDetail = $this->helper->getDetailByNumber($args->getId());
118
        $articleDetailId = $articleDetail->getId();
119
120
        if (!$this->helper->isRemoteArticleDetail($articleDetailId)) {
121
            return;
122
        };
123
124
        $shopProductId = $this->helper->getShopProductId($articleDetailId);
125
        $shopId = $shopProductId->shopId;
126
127
        /**
128
         * @var RemoteShopService $remoteShopService
129
         * @todo: refactor when using 5.2 plugin base.
130
         */
131
        $remoteShopService = Shopware()->Container()->get('swagconnect.remote_shop_service');
132
133
        if ($remoteShopService->isPingRemoteShopSuccessful($shopId)) {
134
            return;
135
        }
136
137
        $this->createBasketInfoMessagesOnFailingRemoteShopPing();
138
139
        // Prevent adding article to basket
140
        return false;
141
    }
142
143
    private function createBasketInfoMessagesOnFailingRemoteShopPing()
144
    {
145
        $infoMessage = Shopware()->Snippets()->getNamespace('backend/connect/view/main')->get(
146
            'connect/basket/addArticleFailedInfoMessage',
147
            'The marketplace product could not be added to the basket because it is not available.'
148
        );
149
150
        Shopware()->Template()
151
            ->assign('basketInfoMessage', $infoMessage)
152
            ->assign('sBasketInfo', $infoMessage);
153
    }
154
155
    /**
156
     * @return \Shopware\Models\Article\Detail
157
     */
158
    public function getDetailRepository()
159
    {
160
        if (!$this->detailRepository) {
161
            $this->detailRepository = $this->modelManager->getRepository(Detail::class);
162
        }
163
164
        return $this->detailRepository;
165
    }
166
167
    /**
168
     * @return \Shopware\Components\Model\ModelRepository|Group
169
     */
170
    public function getCustomerGroupRepository()
171
    {
172
        if (!$this->customerGroupRepository) {
173
            $this->customerGroupRepository = $this->modelManager->getRepository(Group::class);
174
        }
175
176
        return $this->customerGroupRepository;
177
    }
178
179
    /**
180
     * @param \Enlight_Event_EventArgs $args
181
     */
182
    public function preBackendArticle(\Enlight_Event_EventArgs $args)
183
    {
184
        /** @var $subject \Enlight_Controller_Action */
185
        $subject = $args->getSubject();
186
        $request = $subject->Request();
187
188
        switch ($request->getActionName()) {
189
            case 'saveDetail':
190
                if ($request->getParam('standard')) {
191
                    $this->generateMainVariantChange($request->getParam('id'));
192
                }
193
                break;
194
            case 'createConfiguratorVariants':
195
                if (!$articleId = $request->getParam('articleId')) {
196
                    return;
197
                }
198
199
                $this->deleteVariants($articleId);
200
                break;
201
        }
202
    }
203
204
    /**
205
     * @event Enlight_Controller_Action_PostDispatch_Backend_Article
206
     * @param \Enlight_Event_EventArgs $args
207
     */
208
    public function extendBackendArticle(\Enlight_Event_EventArgs $args)
209
    {
210
        /** @var $subject \Enlight_Controller_Action */
211
        $subject = $args->getSubject();
212
        $request = $subject->Request();
213
214
        switch ($request->getActionName()) {
215
            case 'index':
216
                $subject->View()->extendsTemplate(
217
                    'backend/article/connect.js'
218
                );
219
                break;
220
            case 'load':
221
                $subject->View()->extendsTemplate(
222
                    'backend/article/model/attribute_connect.js'
223
                );
224
                $subject->View()->assign('disableConnectPrice', 'true');
225
                $subject->View()->extendsTemplate(
226
                    'backend/article/view/detail/connect_tab.js'
227
                );
228
                $subject->View()->extendsTemplate(
229
                    'backend/article/view/detail/prices_connect.js'
230
                );
231
                $subject->View()->extendsTemplate(
232
                    'backend/article/controller/detail_connect.js'
233
                );
234
                $subject->View()->extendsTemplate(
235
                    'backend/article/view/detail/connect_properties.js'
236
                );
237
                break;
238
            case 'setPropertyList':
239
                // property values are saved in different ajax call then
240
                // property group and this will generate wrong Connect changes.
241
                // after the property values are saved, the temporary property group is no needed
242
                // and it will generate right Connect changes
243
                $articleId = $request->getParam('articleId', null);
244
245
                /** @var ArticleModel $article */
246
                $article = $this->modelManager->find(ArticleModel::class, $articleId);
247
248
                if (!$article) {
249
                    return;
250
                }
251
252
                if (!$article->getPropertyGroup()) {
253
                    return;
254
                }
255
256
                // Check if entity is a connect product
257
                $attribute = $this->helper->getConnectAttributeByModel($article);
258
                if (!$attribute) {
259
                    return;
260
                }
261
262
                // if article is not exported to Connect
263
                // don't need to generate changes
264
                if (!$this->helper->isProductExported($attribute) || !empty($attribute->getShopId())) {
265
                    return;
266
                }
267
268
                if (!$this->hasPriceType()) {
269
                    return;
270
                }
271
272
                $detail = $article->getMainDetail();
273
274
                if ($detail->getAttribute()->getConnectPropertyGroup()) {
275
                    $detail->getAttribute()->setConnectPropertyGroup(null);
276
                    $this->modelManager->persist($detail);
277
                    $this->modelManager->flush();
278
                }
279
280
                $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...
281
                if ($autoUpdateProducts == Config::UPDATE_CRON_JOB) {
282
                    $this->modelManager->getConnection()->update(
283
                        's_plugin_connect_items',
284
                        ['cron_update' => 1],
285
                        ['article_id' => $article->getId()]
286
                    );
287
                } else {
288
                    $sourceIds = $this->modelManager->getConnection()->executeQuery(
289
                        'SELECT source_id FROM s_plugin_connect_items WHERE article_id = ?',
290
                        [$article->getId()]
291
                    )->fetchAll(\PDO::FETCH_COLUMN);
292
                    $this->connectExport->export($sourceIds);
293
                }
294
                break;
295
            case 'createConfiguratorVariants':
296
                // main detail should be updated as well, because shopware won't call lifecycle event
297
                // even postUpdate of Detail. By this way Connect will generate change for main variant,
298
                // otherwise $product->variant property is an empty array
299
                // if main detail is not changed, Connect SDK won't generate change for it.
300
                // ticket CON-3747
301
                if (!$articleId = $request->getParam('articleId')) {
302
                    return;
303
                }
304
305
                $this->regenerateChangesForArticle($articleId);
306
                break;
307
            case 'getPropertyList':
308
                $subject->View()->data = $this->addConnectFlagToProperties(
309
                    $subject->View()->data
310
                );
311
                break;
312
            case 'deleteAllVariants':
313
                if ($articleId = $request->getParam('articleId')) {
314
                    /** @var ArticleModel $article */
315
                    $article = $this->modelManager->find(ArticleModel::class, (int) $articleId);
316
                    if (!$article) {
317
                        return;
318
                    }
319
320
                    $this->deleteVariants($articleId);
321
                }
322
                break;
323
            default:
324
                break;
325
        }
326
    }
327
328
    /**
329
     * @param int $articleId
330
     */
331
    public function regenerateChangesForArticle($articleId)
332
    {
333
        $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...
334
        if ($autoUpdateProducts == Config::UPDATE_MANUAL) {
335
            return;
336
        }
337
338
        /** @var \Shopware\Models\Article\Article $article */
339
        $article = $this->modelManager->getRepository(ArticleModel::class)->find((int) $articleId);
340
        if (!$article) {
341
            return;
342
        }
343
344
        $attribute = $this->helper->getConnectAttributeByModel($article);
345
        if (!$attribute) {
346
            return;
347
        }
348
349
        // Check if entity is a connect product
350
        if (!$this->helper->isProductExported($attribute)) {
351
            return;
352
        }
353
354
        if ($autoUpdateProducts == Config::UPDATE_CRON_JOB) {
355
            $this->connectExport->markArticleForCronUpdate($articleId);
356
357
            return;
358
        }
359
360
        $this->connectExport->export($this->helper->getArticleSourceIds([$articleId]));
361
    }
362
363
    /**
364
     * Delete all variants of given product except main one
365
     *
366
     * @param int $articleId
367
     */
368
    private function deleteVariants($articleId)
369
    {
370
        $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...
371
        if ($autoUpdateProducts == Config::UPDATE_MANUAL) {
372
            return;
373
        }
374
375
        /** @var \Shopware\Models\Article\Article $article */
376
        $article = $this->modelManager->getRepository(ArticleModel::class)->find((int) $articleId);
377
        if (!$article) {
378
            return;
379
        }
380
381
        $connectAttribute = $this->helper->getConnectAttributeByModel($article);
382
        if (!$connectAttribute) {
383
            return;
384
        }
385
386
        // Check if entity is a connect product
387
        if (!$this->helper->isProductExported($connectAttribute)) {
388
            return;
389
        }
390
391
        $mainVariantSourceId = $connectAttribute->getSourceId();
392
        $sourceIds = array_filter(
393
            $this->helper->getArticleSourceIds([$article->getId()]),
394
            function ($sourceId) use ($mainVariantSourceId) {
395
                return $sourceId != $mainVariantSourceId;
396
            }
397
        );
398
399
        foreach ($sourceIds as $sourceId) {
400
            $this->sdk->recordDelete($sourceId);
401
        }
402
403
        $this->connectExport->updateConnectItemsStatus($sourceIds, Attribute::STATUS_DELETE);
404
    }
405
406
    public function addConnectFlagToProperties($data)
407
    {
408
        $groups = [];
409
        foreach ($data as $group) {
410
            $options = [];
411
            foreach ($group['value'] as $value) {
412
                $element = $value;
413
                $optionId = $value['id'];
414
                $valueModel = $this->modelManager->getRepository('Shopware\Models\Property\Value')->find($optionId);
415
416
                $attribute = null;
417
                if ($valueModel) {
418
                    $attribute = $valueModel->getAttribute();
419
                }
420
421
                if ($attribute && $attribute->getConnectIsRemote()) {
422
                    $element['connect'] = true;
423
                } else {
424
                    $element['connect'] = false;
425
                }
426
                $options[] = $element;
427
            }
428
429
            $group['value'] = $options;
430
            $groups[] = $group;
431
        }
432
433
        return $groups;
434
    }
435
436
    /**
437
     * @param $detailId
438
     */
439
    public function generateMainVariantChange($detailId)
440
    {
441
        $detail = $this->getDetailRepository()->findOneBy(['id' => $detailId]);
442
443
        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...
444
            return;
445
        }
446
447
        //if it is already main variant dont generate MakeMainVariant change
448
        if ($detail->getKind() == 1) {
449
            return;
450
        }
451
452
        $attribute = $this->helper->getConnectAttributeByModel($detail);
453
454
        if (!$attribute) {
455
            return;
456
        }
457
        // Check if entity is a connect product
458
        if (!$this->helper->isProductExported($attribute)) {
459
            return;
460
        }
461
462
        if (!$this->hasPriceType()) {
463
            return;
464
        }
465
466
        $groupId = $attribute->getGroupId() ? $attribute->getGroupId() : $attribute->getArticleId();
467
468
        $mainVariant = new MakeMainVariant([
469
            'sourceId' => $attribute->getSourceId(),
470
            'groupId' => $groupId
471
        ]);
472
473
        try {
474
            $this->sdk->makeMainVariant($mainVariant);
475
        } catch (\Exception $e) {
476
            // if sn is not available, proceed without exception
477
        }
478
    }
479
480
    /**
481
     * When saving prices make sure, that the connectPrice is stored in net
482
     *
483
     * @param \Enlight_Hook_HookArgs $args
484
     */
485
    public function enforceConnectPriceWhenSaving(\Enlight_Hook_HookArgs $args)
486
    {
487
        /** @var array $prices */
488
        $prices = $args->getReturn();
489
490
        $connectCustomerGroup = $this->getConnectCustomerGroup();
491
        if (!$connectCustomerGroup) {
492
            return;
493
        }
494
        $connectCustomerGroupKey = $connectCustomerGroup->getKey();
495
        $defaultPrices = [];
496
        foreach ($prices as $key => $priceData) {
497
            if ($priceData['customerGroupKey'] == $connectCustomerGroupKey) {
498
                return;
499
            }
500
            if ($priceData['customerGroupKey'] == 'EK') {
501
                $defaultPrices[] = $priceData;
502
            }
503
        }
504
505
        foreach ($defaultPrices as $price) {
506
            $prices[] = [
507
                'from' => $price['from'],
508
                'to' => $price['to'],
509
                'price' => $price['price'],
510
                'pseudoPrice' => $price['pseudoPrice'],
511
                'basePrice' => $price['basePrice'],
512
                'percent' => $price['percent'],
513
                'customerGroup' => $connectCustomerGroup,
514
                'article' => $price['article'],
515
                'articleDetail' => $price['articleDetail'],
516
            ];
517
        }
518
519
        $args->setReturn($prices);
520
    }
521
522
    /**
523
     * @return \Shopware\Models\Customer\Group|null
524
     */
525 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...
526
    {
527
        $repo = $this->modelManager->getRepository(CustomerGroupAttribute::class);
528
        /** @var \Shopware\Models\Attribute\CustomerGroup $model */
529
        $model = $repo->findOneBy(['connectGroup' => true]);
530
531
        $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...
532
        if ($model && $model->getCustomerGroup()) {
533
            return $model->getCustomerGroup();
534
        }
535
536
        return null;
537
    }
538
539
    /**
540
     * Load article detail
541
     *
542
     * @param \Enlight_Event_EventArgs $args
543
     */
544
    public function extendFrontendArticle(\Enlight_Event_EventArgs $args)
545
    {
546
        /** @var \Enlight_Controller_Request_RequestHttp $request */
547
        $request = $args->getSubject()->Request();
548
        if ($request->getActionName() != 'index') {
549
            return;
550
        }
551
552
        $detailId = (int) $request->sArticleDetail;
553
        if ($detailId === 0) {
554
            return;
555
        }
556
557
        /** @var \Shopware\Models\Article\Detail $detailModel */
558
        $detailModel = $this->modelManager->getRepository(Detail::class)->find($detailId);
559
        if (!$detailModel) {
560
            return;
561
        }
562
563
        $params = [];
564
        /** @var \Shopware\Models\Article\Configurator\Option $option */
565
        foreach ($detailModel->getConfiguratorOptions() as $option) {
566
            $groupId = $option->getGroup()->getId();
567
            $params[$groupId] = $option->getId();
568
        }
569
        $request->setPost('group', $params);
570
    }
571
572
    /**
573
     * Should be possible to buy connect products
574
     * when they're not in stock.
575
     * Depends on remote shop configuration.
576
     *
577
     * @param \Enlight_Event_EventArgs $args
578
     */
579
    public function modifyConnectArticle(\Enlight_Event_EventArgs $args)
580
    {
581
        /** @var \Enlight_Controller_Request_RequestHttp $request */
582
        $request = $args->getSubject()->Request();
583
584
        if ($request->getActionName() != 'index') {
585
            return;
586
        }
587
        $subject = $args->getSubject();
588
        $article = $subject->View()->getAssign('sArticle');
589
        if (!$article) {
590
            return;
591
        }
592
593
        // when article stock is greater than 0
594
        // we don't need to modify it.
595
        if ($article['instock'] > 0) {
596
            return;
597
        }
598
599
        $articleId = $article['articleID'];
600
        $remoteShopId = $this->getRemoteShopId($articleId);
601
        if (!$remoteShopId) {
602
            // article is not imported via Connect
603
            return;
604
        }
605
606
        /** @var \Shopware\Models\Article\Article $articleModel */
607
        $articleModel = $this->modelManager->getRepository(ArticleModel::class)->find($articleId);
608
        if (!$articleModel) {
609
            return;
610
        }
611
612
        $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...
613
        if ($shopConfiguration->sellNotInStock && !$articleModel->getLastStock()) {
614
            // if selNotInStock is = true and article getLastStock = false
615
            // we don't need to modify it
616
            return;
617
        }
618
619
        if (!$shopConfiguration->sellNotInStock && $articleModel->getLastStock()) {
620
            // if sellNotInStock is = false and article getLastStock = true
621
            // we don't need to modify it
622
            return;
623
        }
624
625
        // sellNotInStock is opposite on articleLastStock
626
        // when it's true, lastStock must be false
627
        $articleModel->setLastStock(!$shopConfiguration->sellNotInStock);
628
        $this->modelManager->persist($articleModel);
629
        $this->modelManager->flush();
630
631
        // modify assigned article
632
        if ($shopConfiguration->sellNotInStock) {
633
            $article['laststock'] = false;
634
            $article['instock'] = 100;
635
            $article['isAvailable'] = true;
636
        } else {
637
            $article['laststock'] = true;
638
        }
639
        $subject->View()->assign('sArticle', $article);
640
    }
641
642
    /**
643
     * Not using the default helper-methods here, in order to keep this small and without any dependencies
644
     * to the SDK
645
     *
646
     * @param $articleId
647
     * @return bool|int
648
     */
649
    private function getRemoteShopId($articleId)
650
    {
651
        return $this->modelManager->getConnection()->fetchColumn(
652
            'SELECT shop_id FROM s_plugin_connect_items WHERE article_id = ? AND shop_id IS NOT NULL',
653
            [$articleId]
654
        );
655
    }
656
657
    /**
658
     * @return bool
659
     */
660 View Code Duplication
    private function hasPriceType()
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...
661
    {
662
        if ($this->sdk->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_PURCHASE
663
            || $this->sdk->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_RETAIL
664
            || $this->sdk->getPriceType() === \Shopware\Connect\SDK::PRICE_TYPE_BOTH
665
        ) {
666
            return true;
667
        }
668
669
        return false;
670
    }
671
}
672