Completed
Pull Request — master (#378)
by Stefan
07:18 queued 02:55
created

Helper::getConnectAttributeByModel()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 8.8571
c 0
b 0
f 0
cc 5
eloc 11
nc 5
nop 1
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\Components;
9
10
use Shopware\Connect\Struct\Product;
11
use Shopware\CustomModels\Connect\AttributeRepository;
12
use Shopware\Models\Article\Article as ProductModel;
13
use Shopware\Components\Model\ModelManager;
14
use Doctrine\ORM\Query;
15
use Shopware\CustomModels\Connect\Attribute as ConnectAttribute;
16
use Shopware\CustomModels\Connect\Attribute;
17
use Shopware\Models\Article\Detail as ProductDetail;
18
use Shopware\Models\Article\Unit;
19
use Shopware\Models\Customer\Group;
20
use ShopwarePlugins\Connect\Components\Utils\UnitMapper;
21
use ShopwarePlugins\Connect\Struct\ShopProductId;
22
23
/**
24
 * @category  Shopware
25
 * @package   Shopware\Plugins\SwagConnect
26
 */
27
class Helper
28
{
29
    /**
30
     * @var ModelManager
31
     */
32
    private $manager;
33
34
    /**
35
     * @var CategoryQuery
36
     */
37
    private $connectCategoryQuery;
38
39
    /**
40
     * @var ProductQuery
41
     */
42
    private $connectProductQuery;
43
44
    /**
45
     * @param ModelManager $manager
46
     * @param CategoryQuery
47
     * @param ProductQuery
48
     */
49
    public function __construct(
50
        ModelManager $manager,
51
        CategoryQuery $connectCategoryQuery,
52
        ProductQuery $connectProductQuery
53
    ) {
54
        $this->manager = $manager;
55
        $this->connectCategoryQuery = $connectCategoryQuery;
56
        $this->connectProductQuery = $connectProductQuery;
57
    }
58
59
    /**
60
     * @return Group
61
     */
62
    public function getDefaultCustomerGroup()
63
    {
64
        $repository = $this->manager->getRepository('Shopware\Models\Customer\Group');
65
66
        return $repository->findOneBy(['key' => 'EK']);
67
    }
68
69
    /**
70
     * Returns an article model for a given (sdk) product.
71
     *
72
     * @param Product $product
73
     * @param int $mode
74
     * @return null|ProductModel
75
     */
76
    public function getArticleModelByProduct(Product $product, $mode = Query::HYDRATE_OBJECT)
77
    {
78
        $builder = $this->manager->createQueryBuilder();
79
        $builder->select(['ba', 'a']);
80
        $builder->from('Shopware\CustomModels\Connect\Attribute', 'ba');
81
        $builder->join('ba.article', 'a');
82
83
        $builder->where('ba.shopId = :shopId AND ba.sourceId = :sourceId');
84
        $query = $builder->getQuery();
85
86
        $query->setParameter('shopId', $product->shopId);
87
        $query->setParameter('sourceId', (string) $product->sourceId);
88
        $result = $query->getResult(
89
            $mode
90
        );
91
92
        if (isset($result[0])) {
93
            $attribute = $result[0];
94
95
            return $attribute->getArticle();
96
        }
97
98
        return null;
99
    }
100
101
    /**
102
     * @param Product $product
103
     * @param int $mode
104
     * @return null|ProductDetail
105
     */
106 View Code Duplication
    public function getArticleDetailModelByProduct(Product $product, $mode = Query::HYDRATE_OBJECT)
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...
107
    {
108
        $builder = $this->manager->createQueryBuilder();
109
        $builder->select(['ba', 'd']);
110
        $builder->from('Shopware\CustomModels\Connect\Attribute', 'ba');
111
        $builder->join('ba.articleDetail', 'd');
112
        $builder->leftJoin('d.attribute', 'at');
113
        $builder->where('ba.shopId = :shopId AND ba.sourceId = :sourceId');
114
115
        $query = $builder->getQuery();
116
        $query->setParameter('shopId', $product->shopId);
117
        $query->setParameter('sourceId', (string) $product->sourceId);
118
119
        $result = $query->getResult(
120
            $mode
121
        );
122
123
        if (isset($result[0])) {
124
            /** @var \Shopware\CustomModels\Connect\Attribute $attribute */
125
            $attribute = $result[0];
126
127
            return $attribute->getArticleDetail();
128
        }
129
130
        return null;
131
    }
132
133
    /**
134
     * Get article detail by his number
135
     *
136
     * @param string $number
137
     * @return null|ProductDetail
138
     */
139
    public function getDetailByNumber($number)
140
    {
141
        return $this->manager->getRepository(ProductDetail::class)->findOneBy(['number' => $number]);
142
    }
143
144
    public function getConnectArticleModel($sourceId, $shopId)
145
    {
146
        $builder = $this->manager->createQueryBuilder();
147
        $builder->select(['ba', 'a']);
148
        $builder->from('Shopware\CustomModels\Connect\Attribute', 'ba');
149
        $builder->join('ba.article', 'a');
150
        $builder->join('a.mainDetail', 'd');
151
        $builder->leftJoin('d.attribute', 'at');
152
153
        $builder->where('ba.shopId = :shopId AND ba.sourceId = :sourceId');
154
        $query = $builder->getQuery();
155
156
        $query->setParameter('shopId', $shopId);
157
        $query->setParameter('sourceId', (string) $sourceId);
158
        $result = $query->getResult(
159
            $query::HYDRATE_OBJECT
160
        );
161
162
        if (isset($result[0])) {
163
            $attribute = $result[0];
164
165
            return $attribute->getArticle();
166
        }
167
168
        return null;
169
    }
170
171
    /**
172
     * @param array $orderNumbers
173
     * @return array
174
     */
175 View Code Duplication
    public function getArticleIdsByNumber(array $orderNumbers)
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...
176
    {
177
        $builder = $this->manager->getConnection()->createQueryBuilder();
178
179
        $rows = $builder->select('d.articleID as articleId')
180
            ->from('s_articles_details', 'd')
181
            ->where('d.ordernumber IN (:orderNumbers)')
182
            ->setParameter('orderNumbers', $orderNumbers, \Doctrine\DBAL\Connection::PARAM_STR_ARRAY)
183
            ->execute()
184
            ->fetchAll();
185
186
        return array_map(function ($row) {
187
            return $row['articleId'];
188
        }, $rows);
189
    }
190
191
    /**
192
     * Returns article detail model by
193
     * given sourceId and shopId
194
     *
195
     * @param string $sourceId
196
     * @param int $shopId
197
     * @return null|ProductDetail
198
     */
199
    public function getConnectArticleDetailModel($sourceId, $shopId)
200
    {
201
        $product = new Product(['sourceId' => $sourceId, 'shopId' => $shopId]);
202
203
        return $this->getArticleDetailModelByProduct($product);
204
    }
205
206
    /**
207
     * Helper to update the connect_items table
208
     */
209
    public function updateConnectProducts()
210
    {
211
        // Insert new articles
212
        $sql = "
213
        INSERT INTO `s_plugin_connect_items` (article_id, article_detail_id, source_id)
214
        SELECT a.id, ad.id, IF(ad.kind = 1, a.id, CONCAT(a.id, '-', ad.id)) as sourceID
215
216
        FROM s_articles a
217
218
        LEFT JOIN `s_articles_details` ad
219
        ON a.id = ad.articleId
220
221
        LEFT JOIN `s_plugin_connect_items` bi
222
        ON bi.article_detail_id = ad.id
223
224
225
        WHERE a.id IS NOT NULL
226
        AND ad.id IS NOT NULL
227
        AND bi.id IS NULL
228
        ";
229
230
        $this->manager->getConnection()->exec($sql);
231
232
        // Delete removed articles from s_plugin_connect_items
233
        $sql = '
234
        DELETE bi FROM `s_plugin_connect_items`  bi
235
236
        LEFT JOIN `s_articles_details` ad
237
        ON ad.id = bi.article_detail_id
238
239
        WHERE ad.id IS NULL
240
        ';
241
242
        $this->manager->getConnection()->exec($sql);
243
    }
244
245
    /**
246
     * Returns a remote connectProduct e.g. for checkout maniputlations
247
     *
248
     * @param array $ids
249
     * @param int $shopId
250
     * @return array
251
     */
252
    public function getRemoteProducts(array $ids, $shopId)
253
    {
254
        return $this->connectProductQuery->getRemote($ids, $shopId);
255
    }
256
257
    /**
258
     * Returns a local connectProduct for export
259
     *
260
     * @param array $sourceIds
261
     * @return Product[]
262
     */
263
    public function getLocalProduct(array $sourceIds)
264
    {
265
        return $this->connectProductQuery->getLocal($sourceIds);
266
    }
267
268
    /**
269
     * Does the current basket contain connect products?
270
     *
271
     * @param $session
272
     * @return bool
273
     */
274
    public function hasBasketConnectProducts($session, $userId = null)
275
    {
276
        $connection = $this->manager->getConnection();
277
        $sql = 'SELECT ob.articleID
278
279
            FROM s_order_basket ob
280
281
            INNER JOIN s_plugin_connect_items bi
282
            ON bi.article_id = ob.articleID
283
            AND bi.shop_id IS NOT NULL
284
285
            WHERE ob.sessionID=?
286
            ';
287
        $whereClause = [$session];
288
289
        if ($userId > 0) {
290
            $sql .= ' OR userID=?';
291
            $whereClause[] = $userId;
292
        }
293
294
        $sql .= ' LIMIT 1';
295
296
        $result = $connection->fetchArray($sql, $whereClause);
297
298
        return !empty($result);
299
    }
300
301
    /**
302
     * Will return the connectAttribute for a given model. The model can be an Article\Article or Article\Detail
303
     *
304
     * @param $model ProductModel|ProductDetail
305
     * @return ConnectAttribute
306
     */
307
    public function getConnectAttributeByModel($model)
308
    {
309
        if (!$model->getId()) {
310
            return false;
311
        }
312
        $repository = $this->manager->getRepository('Shopware\CustomModels\Connect\Attribute');
313
314
        if ($model instanceof ProductModel) {
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...
315
            if (!$model->getMainDetail()) {
316
                return false;
317
            }
318
319
            return $repository->findOneBy(['articleDetailId' => $model->getMainDetail()->getId()]);
320
        } elseif ($model instanceof ProductDetail) {
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...
321
            return $repository->findOneBy(['articleDetailId' => $model->getId()]);
322
        }
323
324
        return false;
325
    }
326
327
    /**
328
     * Returns connectAttributes for all article details by given article object
329
     *
330
     * @param ProductModel $article
331
     * @return \Shopware\CustomModels\Connect\Attribute[]
332
     */
333
    public function getConnectAttributesByArticle(ProductModel $article)
334
    {
335
        $builder = $this->manager->createQueryBuilder();
336
        $builder->select(['connectAttribute', 'detail']);
337
        $builder->from('Shopware\CustomModels\Connect\Attribute', 'connectAttribute');
338
        $builder->innerJoin('connectAttribute.articleDetail', 'detail');
339
340
        $builder->where('connectAttribute.articleId = :articleId');
341
        $query = $builder->getQuery();
342
343
        $query->setParameter('articleId', $article->getId());
344
345
        return $query->getResult();
346
    }
347
348
    /**
349
     * Returns true when product is exported to Connect
350
     *
351
     * @param Attribute $connectAttribute
352
     * @return bool
353
     */
354
    public function isProductExported(Attribute $connectAttribute)
355
    {
356
        $status = $connectAttribute->getExportStatus();
357
        if ($connectAttribute->isExported()) {
358
            return true;
359
        }
360
361
        if ($status == Attribute::STATUS_INSERT) {
362
            return true;
363
        }
364
365
        if ($status == Attribute::STATUS_UPDATE) {
366
            return true;
367
        }
368
369
        if ($status == Attribute::STATUS_SYNCED) {
370
            return true;
371
        }
372
373
        return false;
374
    }
375
376
    /**
377
     * Verifies that at least one variant from
378
     * same article is exported.
379
     *
380
     * @param Attribute $connectAttribute
381
     * @return bool
382
     */
383
    public function hasExportedVariants(Attribute $connectAttribute)
384
    {
385
        $builder = $this->manager->getConnection()->createQueryBuilder();
386
        $builder->select('COUNT(spci.id)')
387
            ->from('s_plugin_connect_items', 'spci')
388
            ->where('spci.article_id = :articleId AND spci.export_status IN (:exportStatus) AND spci.shop_id IS NULL')
389
            ->setParameter('articleId', $connectAttribute->getArticleId(), \PDO::PARAM_INT)
390
            ->setParameter(
391
                ':exportStatus',
392
                [Attribute::STATUS_INSERT, Attribute::STATUS_UPDATE, Attribute::STATUS_SYNCED],
393
                \Doctrine\DBAL\Connection::PARAM_STR_ARRAY
394
            );
395
396
        return $builder->execute()->fetchColumn() > 0;
397
    }
398
399
    /**
400
     * Helper method to create a connect attribute on the fly
401
     *
402
     * @param $model
403
     * @throws \RuntimeException
404
     * @return ConnectAttribute
405
     */
406
    public function getOrCreateConnectAttributeByModel($model)
407
    {
408
        $attribute = $this->getConnectAttributeByModel($model);
409
410
        if (!$attribute) {
411
            $attribute = new ConnectAttribute();
412
            $attribute->setPurchasePriceHash('');
413
            $attribute->setOfferValidUntil('');
414
            $attribute->setStream('');
415
416
            if ($model instanceof ProductModel) {
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...
417
                $attribute->setArticle($model);
418
                $attribute->setArticleDetail($model->getMainDetail());
419
                $attribute->setSourceId(
420
                    $this->generateSourceId($model->getMainDetail())
421
                );
422
            } elseif ($model instanceof ProductDetail) {
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...
423
                $attribute->setArticle($model->getArticle());
424
                $attribute->setArticleDetail($model);
425
                $attribute->setSourceId(
426
                    $this->generateSourceId($model)
427
                );
428
            } else {
429
                throw new \RuntimeException('Passed model needs to be an article or an article detail');
430
            }
431
            $this->manager->persist($attribute);
432
            $this->manager->flush($attribute);
433
        }
434
435
        return $attribute;
436
    }
437
438
    /**
439
     * Returns connect attributes for article
440
     * and all variants.
441
     * If connect attribute does not exist
442
     * it will be created.
443
     *
444
     * @param ProductModel $article
445
     * @return array
446
     */
447
    public function getOrCreateConnectAttributes(ProductModel $article)
448
    {
449
        $attributes = [];
450
        /** @var \Shopware\Models\Article\Detail $detail */
451
        foreach ($article->getDetails() as $detail) {
452
            $attributes[] = $this->getOrCreateConnectAttributeByModel($detail);
453
        }
454
455
        return $attributes;
456
    }
457
458
    /**
459
     * Generate sourceId
460
     *
461
     * @param ProductDetail $detail
462
     * @return string
463
     */
464
    public function generateSourceId(ProductDetail $detail)
465
    {
466
        if ($detail->getKind() == 1) {
467
            $sourceId = (string) $detail->getArticle()->getId();
468
        } else {
469
            $sourceId = sprintf(
470
                '%s-%s',
471
                $detail->getArticle()->getId(),
472
                $detail->getId()
473
            );
474
        }
475
476
        return $sourceId;
477
    }
478
479
    /**
480
     * @param $id
481
     * @return array
482
     */
483
    public function getConnectCategoryForProduct($id)
484
    {
485
        return $this->connectCategoryQuery->getConnectCategoryForProduct($id);
486
    }
487
488
    public function getMostRelevantConnectCategory($categories)
489
    {
490
        usort(
491
            $categories,
492
            [
493
                $this->connectCategoryQuery->getRelevanceSorter(),
494
                'sortConnectCategoriesByRelevance'
495
            ]
496
        );
497
498
        return array_pop($categories);
499
    }
500
501
    /**
502
     * Defines the update flags
503
     *
504
     * @return array
505
     */
506
    public function getUpdateFlags()
507
    {
508
        return [2 => 'shortDescription', 4 => 'longDescription', 8 => 'name', 16 => 'image', 32 => 'price', 64 => 'imageInitialImport', 128 => 'additionalDescription'];
509
    }
510
511
    /**
512
     * Returns shopware unit entity
513
     *
514
     * @param $unitKey
515
     * @return \Shopware\Models\Article\Unit
516
     */
517
    public function getUnit($unitKey)
518
    {
519
        $repository = $this->manager->getRepository('Shopware\Models\Article\Unit');
520
521
        return $repository->findOneBy(['unit' => $unitKey]);
522
    }
523
524
    /**
525
     * Clear article cache
526
     */
527
    public function clearArticleCache($articleId)
528
    {
529
        Shopware()->Events()->notify(
530
            'Shopware_Plugins_HttpCache_InvalidateCacheId',
531
            ['cacheId' => 'a' . $articleId]
532
        );
533
    }
534
535
    /**
536
     * Replace unit and ref quantity
537
     * @param $products
538
     * @return mixed
539
     */
540
    public function prepareConnectUnit($products)
541
    {
542
        foreach ($products as &$p) {
543
            if ($p->attributes['unit']) {
544
                $configComponent = ConfigFactory::getConfigInstance();
545
                /** @var \ShopwarePlugins\Connect\Components\Utils\UnitMapper $unitMapper */
546
                $unitMapper = new UnitMapper(
547
                    $configComponent,
548
                    $this->manager
549
                );
550
551
                $p->attributes['unit'] = $unitMapper->getConnectUnit($p->attributes['unit']);
552
            }
553
554
            if ($p->attributes['ref_quantity']) {
555
                $intRefQuantity = (int) $p->attributes['ref_quantity'];
556
                if ($p->attributes['ref_quantity'] - $intRefQuantity <= 0.0001) {
557
                    $p->attributes['ref_quantity'] = $intRefQuantity;
558
                }
559
            }
560
        }
561
562
        return $products;
563
    }
564
565
    /**
566
     * Removes connect reservation from session
567
     */
568
    public function clearConnectReservation()
569
    {
570
        Shopware()->Session()->connectReservation = null;
571
    }
572
573
    /**
574
     * Collect sourceIds by given article ids
575
     *
576
     * @param array $articleIds
577
     * @return array
578
     */
579
    public function getArticleSourceIds(array $articleIds)
580
    {
581
        if (empty($articleIds)) {
582
            return [];
583
        }
584
585
        /** @var AttributeRepository $repo */
586
        $repo = $this->manager->getRepository(ConnectAttribute::class);
587
588
        return array_merge(
589
            $repo->findSourceIds($articleIds, 1),
590
            $repo->findSourceIds($articleIds, 2)
591
        );
592
    }
593
594
    /**
595
     * Get ShopProductId struct by given article detail id
596
     * It contains product sourceId and shopId.
597
     * If $articleDetailId is local product, $shopProductId->shopId will be null.
598
     *
599
     * @param int $articleDetailId
600
     * @return ShopProductId
601
     */
602
    public function getShopProductId($articleDetailId)
603
    {
604
        $articleDetailId = (int) $articleDetailId;
605
        $builder = $this->manager->getConnection()->createQueryBuilder();
606
        $builder->select('items.source_id as sourceId, items.shop_id as shopId')
607
            ->from('s_plugin_connect_items', 'items')
608
            ->where('items.article_detail_id = :articleDetailIds')
609
            ->setParameter(':articleDetailIds', $articleDetailId);
610
611
        $result = $builder->execute()->fetch(\PDO::FETCH_ASSOC);
612
613
        return new ShopProductId($result);
614
    }
615
616
    /**
617
     * Check if given articleDetailId is remote product
618
     *
619
     * @param int $articleDetailId
620
     * @return bool
621
     */
622
    public function isRemoteArticleDetail($articleDetailId)
623
    {
624
        $articleDetailId = (int) $articleDetailId;
625
        $articleDetailRepository = $this->manager->getRepository('Shopware\Models\Article\Detail');
626
        /** @var \Shopware\Models\Article\Detail $detail */
627
        $detail = $articleDetailRepository->find($articleDetailId);
628
        if (!$detail) {
629
            return false;
630
        }
631
632
        $connectAttribute = $this->getConnectAttributeByModel($detail);
633
        if (!$connectAttribute) {
634
            return false;
635
        }
636
637
        return ($connectAttribute->getShopId() != null);
638
    }
639
640
    /**
641
     * Check if given articleDetailId is remote product
642
     *
643
     * @param int $articleDetailId
644
     * @return bool
645
     */
646
    public function isRemoteArticleDetailDBAL($articleDetailId)
647
    {
648
        $articleDetailId = (int) $articleDetailId;
649
        $builder = $this->manager->getConnection()->createQueryBuilder();
650
        $builder->select('items.shop_id')
651
            ->from('s_plugin_connect_items', 'items')
652
            ->where('items.article_detail_id = :articleDetailId')
653
            ->setParameter(':articleDetailId', $articleDetailId);
654
655
        return (bool) $builder->execute()->fetchColumn();
656
    }
657
658
    /**
659
     * Extract article ID and detail ID
660
     * from source ID
661
     *
662
     * @param $sourceId
663
     * @return array
664
     */
665
    public function explodeArticleId($sourceId)
666
    {
667
        $articleId = explode('-', $sourceId);
668
669
        if (isset($articleId[1]) && isset($articleId[1])) {
670
            return $articleId;
671
        }
672
673
        return [
674
            $articleId[0]
675
        ];
676
    }
677
678
    /**
679
     * Creates Shopware product model
680
     *
681
     * @param Product $product
682
     * @return ProductModel
683
     */
684
    public function createProductModel(Product $product)
685
    {
686
        //todo@sb: Add test
687
        $model = new ProductModel();
688
        $model->setActive(false);
689
        $model->setName($product->title);
690
        $this->manager->persist($model);
691
692
        return $model;
693
    }
694
695
    /**
696
     * Returns main article detail by given groupId
697
     *
698
     * @param $product
699
     * @param int $mode
700
     * @return null|ProductModel
701
     */
702 View Code Duplication
    public function getArticleByRemoteProduct(Product $product, $mode = Query::HYDRATE_OBJECT)
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...
703
    {
704
        $builder = $this->manager->createQueryBuilder();
705
        $builder->select(['ba', 'd']);
706
        $builder->from('Shopware\CustomModels\Connect\Attribute', 'ba');
707
        $builder->join('ba.articleDetail', 'd');
708
        $builder->leftJoin('d.attribute', 'at');
709
710
        $builder->where('ba.groupId = :groupId AND ba.isMainVariant = 1 AND ba.shopId = :shopId');
711
        $query = $builder->getQuery();
712
713
        $query->setParameter('groupId', $product->groupId);
714
        $query->setParameter('shopId', $product->shopId);
715
        $result = $query->getResult(
716
            $mode
717
        );
718
719
        if (isset($result[0])) {
720
            /** @var \Shopware\CustomModels\Connect\Attribute $attribute */
721
            $attribute = $result[0];
722
723
            return $attribute->getArticle();
724
        }
725
726
        return null;
727
    }
728
729
    /**
730
     * @param int $articleId
731
     * @return array
732
     */
733
    public function getSourceIdsFromArticleId($articleId)
734
    {
735
        $rows = $this->manager->getConnection()->fetchAll(
736
            'SELECT source_id FROM s_plugin_connect_items WHERE article_id = ? AND exported = 1',
737
            [$articleId]
738
        );
739
740
        return array_map(function ($row) {
741
            return $row['source_id'];
742
        }, $rows);
743
    }
744
745
    /**
746
     * @param Unit $localUnit
747
     * @param string $remoteUnit
748
     */
749
    public function updateUnitInRelatedProducts(Unit $localUnit, $remoteUnit)
750
    {
751
        $statement = $this->manager->getConnection()->prepare('UPDATE s_articles_details sad
752
            LEFT JOIN s_articles_attributes saa ON sad.id = saa.articledetailsID
753
            SET sad.unitID = :unitId
754
            WHERE saa.connect_remote_unit = :remoteUnit');
755
756
        $statement->bindValue(':unitId', $localUnit->getId(), \PDO::PARAM_INT);
757
        $statement->bindValue(':remoteUnit', $remoteUnit, \PDO::PARAM_STR);
758
759
        $statement->execute();
760
    }
761
762
    /**
763
     * Checks whether given sourceId is main variant.
764
     * Works only with local products.
765
     * SourceIds pattern is articleId-variantId (58-142)
766
     *
767
     * For remote product check is_main_variant flag in
768
     * s_plugin_connect_items
769
     *
770
     * @param string $sourceId
771
     * @return bool
772
     */
773
    public function isMainVariant($sourceId)
774
    {
775
        $isMainVariant = $this->manager->getConnection()->fetchColumn(
776
            'SELECT d.kind
777
              FROM s_plugin_connect_items spci
778
              LEFT JOIN s_articles_details d ON spci.article_detail_id = d.id
779
              WHERE source_id = ?',
780
            [$sourceId]
781
        );
782
783
        if ($isMainVariant != 1) {
784
            return false;
785
        }
786
787
        return true;
788
    }
789
790
    /**
791
     * @return array
792
     */
793 View Code Duplication
    public function getAllNonConnectArticleIds()
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...
794
    {
795
        $builder = $this->manager->getConnection()->createQueryBuilder();
796
        $builder->select('DISTINCT spci.article_id');
797
        $builder->from('s_plugin_connect_items', 'spci');
798
        $builder->where('spci.shop_id IS NULL');
799
800
        $result = $builder->execute()->fetchAll();
801
802
        return array_map(function ($row) {
803
            return $row['article_id'];
804
        }, $result);
805
    }
806
}
807