Completed
Pull Request — master (#448)
by Jonas
03:00
created

ProductFromShop::reserve()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 5
nc 1
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 Enlight_Event_EventManager;
11
use Shopware\Connect\Gateway;
12
use Shopware\Connect\ProductFromShop as ProductFromShopBase;
13
use Shopware\Connect\Struct\Order;
14
use Shopware\Connect\Struct\Product;
15
use Shopware\Connect\Struct\Address;
16
use Shopware\Models\Dispatch\Dispatch;
17
use Shopware\Models\Order as OrderModel;
18
use Shopware\Models\Attribute\OrderDetail as OrderDetailAttributeModel;
19
use Shopware\Models\Customer as CustomerModel;
20
use Shopware\Components\Model\ModelManager;
21
use Shopware\Components\Random;
22
use Shopware\Connect\Struct\Change\FromShop\Availability;
23
use Shopware\Connect\Struct\Change\FromShop\Insert;
24
use Shopware\Connect\Struct\Change\FromShop\Update;
25
use Shopware\Connect\Struct\PaymentStatus;
26
use Shopware\Connect\Struct\Shipping;
27
use Shopware\CustomModels\Connect\Attribute;
28
use ShopwarePlugins\Connect\Components\ProductStream\ProductStreamService;
29
use Shopware\Connect\Struct\Message;
30
31
/**
32
 * The interface for products exported *to* connect *from* the local shop
33
 *
34
 * @category  Shopware
35
 * @package   Shopware\Plugins\SwagConnect
36
 */
37
class ProductFromShop implements ProductFromShopBase
38
{
39
    /**
40
     * @var Helper
41
     */
42
    private $helper;
43
44
    /**
45
     * @var ModelManager
46
     */
47
    private $manager;
48
49
    /**
50
     * @var \Shopware\Connect\Gateway
51
     */
52
    private $gateway;
53
54
    /**
55
     * @var Logger
56
     */
57
    private $logger;
58
59
    /**
60
     * @var Enlight_Event_EventManager
61
     */
62
    private $eventManager;
63
64
    /**
65
     * @param Helper $helper
66
     * @param ModelManager $manager
67
     * @param Gateway $gateway
68
     * @param Logger $logger
69
     * @param Enlight_Event_EventManager $eventManager
70
     */
71
    public function __construct(
72
        Helper $helper,
73
        ModelManager $manager,
74
        Gateway $gateway,
75
        Logger $logger,
76
        Enlight_Event_EventManager $eventManager
77
    ) {
78
        $this->helper = $helper;
79
        $this->manager = $manager;
80
        $this->gateway = $gateway;
81
        $this->logger = $logger;
82
        $this->eventManager = $eventManager;
83
    }
84
85
    /**
86
     * Get product data
87
     *
88
     * Get product data for all the source IDs specified in the given string
89
     * array.
90
     *
91
     * @param string[] $sourceIds
92
     * @return Product[]
93
     */
94
    public function getProducts(array $sourceIds)
95
    {
96
        return $this->helper->getLocalProduct($sourceIds);
97
    }
98
99
    /**
100
     * Get all IDs of all exported products
101
     *
102
     * @throws \BadMethodCallException
103
     * @return string[]
104
     */
105
    public function getExportedProductIDs()
106
    {
107
        throw new \BadMethodCallException('Not implemented');
108
    }
109
110
    /**
111
     * Reserve a product in shop for purchase
112
     *
113
     * @param Order $order
114
     * @throws \Exception Abort reservation by throwing an exception here.
115
     * @return void
116
     */
117
    public function reserve(Order $order)
118
    {
119
        $this->eventManager->notify(
120
            'Connect_Supplier_Reservation_Before',
121
            [
122
                'subject' => $this,
123
                'order' => $order
124
            ]
125
        );
126
    }
127
128
    /**
129
     * Create order in shopware
130
     * Wraps the actual order process into a transaction
131
     *
132
     *
133
     * @param Order $order
134
     * @throws \Exception Abort buy by throwing an exception,
135
     *                    but only in very important cases.
136
     *                    Do validation in {@see reserve} instead.
137
     * @return string
138
     */
139
    public function buy(Order $order)
140
    {
141
        $this->manager->beginTransaction();
142
        try {
143
            $order = $this->eventManager->filter('Connect_Components_ProductFromShop_Buy_OrderFilter', $order);
144
145
            $this->validateBilling($order->billingAddress);
146
            $orderNumber = $this->doBuy($order);
147
148
            $this->manager->commit();
149
        } catch (\Exception $e) {
150
            $this->manager->rollback();
151
            throw $e;
152
        }
153
154
        return $orderNumber;
155
    }
156
157
    /**
158
     * Actually creates the remote order in shopware.
159
     *
160
     * @param Order $order
161
     * @return string
162
     */
163
    public function doBuy(Order $order)
164
    {
165
        $this->manager->clear();
166
167
        $detailStatus = $this->manager->find('Shopware\Models\Order\DetailStatus', 0);
168
        $status = $this->manager->find('Shopware\Models\Order\Status', 0);
169
        $shop = $this->manager->find('Shopware\Models\Shop\Shop', 1);
170
        $number = 'SC-' . $order->orderShop . '-' . $order->localOrderId;
171
172
        $repository = $this->manager->getRepository('Shopware\Models\Payment\Payment');
173
        $payment = $repository->findOneBy([
174
            'name' => 'invoice',
175
        ]);
176
177
        // todo: Create the OrderModel without previous plain SQL
178
        //$model = new OrderModel\Order();
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
179
        $sql = 'INSERT INTO `s_order` (`ordernumber`, `cleared`) VALUES (?, 17);';
180
        Shopware()->Db()->query($sql, [$number]);
181
        $modelId = Shopware()->Db()->lastInsertId();
182
        /** @var $model \Shopware\Models\Order\Order */
183
        $model = $this->manager->find('Shopware\Models\Order\Order', $modelId);
184
185
        $attribute = new \Shopware\Models\Attribute\Order;
186
        $attribute->setConnectOrderId($order->localOrderId);
187
        $attribute->setConnectShopId($order->orderShop);
188
        $model->setAttribute($attribute);
189
190
        $model->fromArray([
191
            'number' => $number,
192
            'invoiceShipping' => $order->grossShippingCosts,
0 ignored issues
show
Bug introduced by
The property grossShippingCosts does not seem to exist. Did you mean shipping?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
193
            'invoiceShippingNet' => $order->shippingCosts,
0 ignored issues
show
Bug introduced by
The property shippingCosts does not seem to exist. Did you mean shipping?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
194
            'currencyFactor' => 1,
195
            'orderStatus' => $status,
196
            'shop' => $shop,
197
            'languageSubShop' => $shop,
198
            'payment' => $payment,
199
            'currency' => 'EUR',
200
            'orderTime' => 'now'
201
        ]);
202
        $items = [];
203
        $connectAttributeRepository = $this->manager->getRepository('Shopware\CustomModels\Connect\Attribute');
204
205
        /** @var \Shopware\Connect\Struct\OrderItem $orderItem */
206
        foreach ($order->products as $orderItem) {
207
            $product = $orderItem->product;
208
            /** @var \Shopware\CustomModels\Connect\Attribute $connectAttribute */
209
            $connectAttribute = $connectAttributeRepository->findOneBy([
210
                'sourceId' => $product->sourceId,
211
                'shopId' => null,
212
            ]);
213
            if (!$connectAttribute) {
214
                $this->logger->write(
215
                    true,
216
                    sprintf('Detail with sourceId: %s does not exist', $product->sourceId),
217
                    null,
218
                    true
219
                );
220
                continue;
221
            }
222
223
            /** @var $detail \Shopware\Models\Article\Detail */
224
            $detail = $connectAttribute->getArticleDetail();
225
            /** @var $productModel \Shopware\Models\Article\Article */
226
            $productModel = $detail->getArticle();
227
            $item = new OrderModel\Detail();
228
            $item->fromArray([
229
                'articleId' => $productModel->getId(),
230
                'quantity' => $orderItem->count,
231
                'orderId' => $model->getId(),
232
                'number' => $model->getNumber(),
233
                'articleNumber' => $detail->getNumber(),
234
                'articleName' => $product->title,
235
                'price' => $this->calculatePrice($product),
236
                'taxRate' => $product->vat * 100,
237
                'status' => $detailStatus,
238
                'attribute' => new OrderDetailAttributeModel()
239
            ]);
240
            $items[] = $item;
241
        }
242
        $model->setDetails($items);
243
244
        $email = $order->billingAddress->email;
245
246
        $password = Random::getAlphanumericString(30);
247
248
        $repository = $this->manager->getRepository('Shopware\Models\Customer\Customer');
249
        $customer = $repository->findOneBy([
250
            'email' => $email
251
        ]);
252
        if ($customer === null) {
253
            $customer = new CustomerModel\Customer();
254
            $customer->fromArray([
255
                'active' => true,
256
                'email' => $email,
257
                'password' => $password,
258
                'accountMode' => 1,
259
                'shop' => $shop,
260
                'paymentId' => $payment->getId(),
261
            ]);
262
        }
263
        if ($customer->getBilling() === null) {
264
            $billing = new CustomerModel\Billing();
265
            $customer->setBilling($billing);
266
        } else {
267
            $billing = $customer->getBilling();
268
        }
269
270
        $billing->fromArray($this->getAddressData(
271
            $order->billingAddress
272
        ));
273
        $this->manager->persist($customer);
274
275
        $model->setCustomer($customer);
276
277
        $billing = new OrderModel\Billing();
278
        $billing->setCustomer($customer);
279
        $billing->fromArray($this->getAddressData(
280
                $order->billingAddress
281
        ));
282
        $model->setBilling($billing);
283
284
        $shipping = new OrderModel\Shipping();
285
        $shipping->setCustomer($customer);
286
        $shipping->fromArray($this->getAddressData(
287
            $order->deliveryAddress
288
        ));
289
        $model->setShipping($shipping);
290
291
        $model->calculateInvoiceAmount();
292
293
        $dispatchRepository = $this->manager->getRepository('Shopware\Models\Dispatch\Dispatch');
294
        $dispatch = $dispatchRepository->findOneBy([
295
            'name' => $order->shipping->service
296
        ]);
297
        if ($dispatch) {
298
            $model->setDispatch($dispatch);
299
        }
300
301
        $this->eventManager->notify(
302
            'Connect_Supplier_Buy_Before',
303
            [
304
                'subject' => $this,
305
                'order' => $order
306
            ]
307
        );
308
309
        $this->manager->flush();
310
311
        return $model->getNumber();
312
    }
313
314
    /**
315
     * Calculate the price (including VAT) that the from shop needs to pay.
316
     *
317
     * This is most likely NOT the price the customer itself has to pay.
318
     *
319
     * @return float
320
     */
321
    private function calculatePrice($product)
322
    {
323
        return $product->purchasePrice * ($product->vat + 1);
324
    }
325
326
    /**
327
     * @param Address $address
328
     * @return array
329
     */
330
    private function getAddressData(Address $address)
331
    {
332
        $repository = 'Shopware\Models\Country\Country';
333
        $repository = $this->manager->getRepository($repository);
334
        /** @var $country \Shopware\Models\Country\Country */
335
        $country = $repository->findOneBy([
336
            'iso3' => $address->country
337
        ]);
338
339
        return [
340
            'company' => $address->company ?: '',
341
            'department' => $address->department ?: '',
342
            'additionalAddressLine1' => $address->additionalAddressLine1 ?: '',
343
            'additionalAddressLine2' => $address->additionalAddressLine2 ?: '',
344
            'salutation' => 'mr',
345
            'lastName' => $address->surName,
346
            'firstName' => $address->firstName,
347
            'city' => $address->city,
348
            'zipCode' => $address->zip,
349
            'street' => $address->street,
350
            'streetNumber' => $address->streetNumber,
351
            'phone' => $address->phone,
352
            'country' => $country
353
        ];
354
    }
355
356
    public function updatePaymentStatus(PaymentStatus $status)
357
    {
358
        // $paymentStatus->localOrderId is actually ordernumber for this shop
359
        // e.g. BP-35-20002
360
        $repository = $this->manager->getRepository('Shopware\Models\Order\Order');
361
        $order = $repository->findOneBy(['number' => $status->localOrderId]);
362
363
        if ($order) {
364
            $paymentStatusRepository = $this->manager->getRepository('Shopware\Models\Order\Status');
365
            /** @var \Shopware\Models\Order\Status $orderPaymentStatus */
366
            $orderPaymentStatus = $paymentStatusRepository->findOneBy(
367
                ['name' => 'sc_' . $status->paymentStatus]
368
            );
369
370
            if ($orderPaymentStatus) {
371
                $order->setPaymentStatus($orderPaymentStatus);
372
373
                $this->eventManager->notify(
374
                    'Connect_Supplier_Update_PaymentStatus_Before',
375
                    [
376
                        'subject' => $this,
377
                        'paymentStatus' => $status,
378
                        'order' => $order
379
                    ]
380
                );
381
382
                $this->manager->persist($order);
383
                $this->manager->flush();
384
            } else {
385
                $this->logger->write(
386
                    true,
387
                    sprintf(
388
                        'Payment status "%s" not found',
389
                        $status->paymentStatus
390
                    ),
391
                    sprintf(
392
                        'Order with id "%s"',
393
                        $status->localOrderId
394
                    )
395
                );
396
            }
397
        } else {
398
            $this->logger->write(
399
                true,
400
                sprintf(
401
                    'Order with id "%s" not found',
402
                    $status->localOrderId
403
                ),
404
                serialize($status)
405
            );
406
        }
407
    }
408
409
    public function calculateShippingCosts(Order $order)
410
    {
411 View Code Duplication
        if (!$order->deliveryAddress) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
412
            return new Shipping([
413
                'isShippable' => false,
414
                'messages' => [
415
                    new Message([
416
                        'message' => 'delivery_address_empty'
417
                    ])
418
                ]
419
            ]);
420
        }
421
422
        $countryIso3 = $order->deliveryAddress->country;
423
        $country = $this->manager->getRepository('Shopware\Models\Country\Country')->findOneBy(['iso3' => $countryIso3]);
424
425 View Code Duplication
        if (!$country) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
426
            return new Shipping([
427
                'isShippable' => false,
428
                'messages' => [
429
                    new Message([
430
                        'message' => 'order_not_shippable_to_country',
431
                        'values' => [
432
                            'country' => $countryIso3,
433
                        ]
434
                    ])
435
                ]
436
            ]);
437
        }
438
439
        if (count($order->orderItems) == 0) {
440
            throw new \InvalidArgumentException(
441
                'ProductList is not allowed to be empty'
442
            );
443
        }
444
445
        /* @var \Shopware\Models\Shop\Shop $shop */
446
        $shop = $this->manager->getRepository('Shopware\Models\Shop\Shop')->getActiveDefault();
447 View Code Duplication
        if (!$shop) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
448
            return new Shipping([
449
                'isShippable' => false,
450
                'messages' => [
451
                    new Message([
452
                        'message' => 'default_shop_not_found'
453
                    ])
454
                ]
455
            ]);
456
        }
457
        $shop->registerResources(Shopware()->Container()->get('bootstrap'));
458
459
        /** @var /Enlight_Components_Session_Namespace $session */
0 ignored issues
show
Documentation introduced by
The doc-type /Enlight_Components_Session_Namespace could not be parsed: Unknown type name "/Enlight_Components_Session_Namespace" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
460
        $session = Shopware()->Session();
461
        $sessionId = uniqid('connect_remote');
462
        $session->offsetSet('sSESSION_ID', $sessionId);
463
464
        $repository = $this->manager->getRepository('Shopware\CustomModels\Connect\Attribute');
465
        $products = [];
466
        /** @var \Shopware\Connect\Struct\OrderItem $orderItem */
467
        foreach ($order->orderItems as $orderItem) {
468
            $attributes = $repository->findBy(['sourceId' => [$orderItem->product->sourceId], 'shopId' => null]);
469
            if (count($attributes) === 0) {
470
                continue;
471
            }
472
473
            $products[] = [
474
                'ordernumber' => $attributes[0]->getArticleDetail()->getNumber(),
475
                'quantity' => $orderItem->count,
476
            ];
477
        }
478
479
        /** @var \Shopware\CustomModels\Connect\Attribute $attribute */
480
        foreach ($products as $product) {
481
            Shopware()->Modules()->Basket()->sAddArticle($product['ordernumber'], $product['quantity']);
482
        }
483
484
        $shippingMethods = Shopware()->Modules()->Admin()->sGetPremiumDispatches($country->getId());
485 View Code Duplication
        if (empty($shippingMethods)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
486
            return new Shipping([
487
                'isShippable' => false,
488
                'messages' => [
489
                    new Message([
490
                        'message' => 'order_not_shippable_to_country',
491
                        'values' => [
492
                            'country' => $countryIso3,
493
                        ]
494
                    ])
495
                ]
496
            ]);
497
        }
498
499
        $shippingMethod = reset($shippingMethods);
500
501
        /** @var Dispatch $shipping */
502
        $shipping = $this->manager->getRepository(Dispatch::class)->find($shippingMethod['id']);
503
504 View Code Duplication
        if (!$shipping) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
505
            return new Shipping([
506
                'isShippable' => false,
507
                'messages' => [
508
                    new Message([
509
                        'message' => 'default_shipping_not_found'
510
                    ])
511
                ]
512
            ]);
513
        }
514
515
        $session->offsetSet('sDispatch', $shipping->getId());
516
517
        $result = Shopware()->Modules()->Admin()->sGetPremiumShippingcosts(['id' => $country->getId()]);
518 View Code Duplication
        if (!is_array($result)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
519
            return new Shipping([
520
                'isShippable' => false,
521
                'messages' => [
522
                    new Message([
523
                        'message' => 'checkout_not_possible'
524
                    ])
525
                ]
526
            ]);
527
        }
528
529
        $sql = 'DELETE FROM s_order_basket WHERE sessionID=?';
530
        Shopware()->Db()->executeQuery($sql, [
531
            $sessionId,
532
        ]);
533
534
        $shippingReturn = new Shipping([
535
            'shopId' => $this->gateway->getShopId(),
536
            'service' => $shipping->getName(),
537
            'shippingCosts' => floatval($result['netto']),
538
            'grossShippingCosts' => floatval($result['brutto']),
539
        ]);
540
541
        $this->eventManager->notify(
542
            'Connect_Supplier_Get_Shipping_After',
543
            [
544
                'subject' => $this,
545
                'shipping' => $shippingReturn,
546
                'order' => $order
547
            ]
548
        );
549
550
        return $shippingReturn;
551
    }
552
553
    /**
554
     * Perform sync changes to fromShop
555
     *
556
     * @param string $since
557
     * @param \Shopware\Connect\Struct\Change[] $changes
558
     * @return void
559
     */
560
    public function onPerformSync($since, array $changes)
561
    {
562
        $this->manager->getConnection()->beginTransaction();
563
564
        $statusSynced = Attribute::STATUS_SYNCED;
565
        $statusInsert = Attribute::STATUS_INSERT;
566
        $statusUpdate = Attribute::STATUS_UPDATE;
567
        $statusDelete = Attribute::STATUS_DELETE;
568
        try {
569
            if ($since) {
570
                $this->manager->getConnection()->executeQuery(
571
                    'UPDATE s_plugin_connect_items
572
                    SET export_status = ?
573
                    WHERE revision <= ?
574
                    AND ( export_status = ? OR export_status = ? )',
575
                    [$statusSynced, $since, $statusInsert, $statusUpdate]
576
                );
577
578
                $this->manager->getConnection()->executeQuery(
579
                    'UPDATE s_plugin_connect_items
580
                    SET export_status = ?
581
                    WHERE revision <= ?
582
                    AND export_status = ?',
583
                    [null, $since, $statusDelete]
584
                );
585
            } else {
586
                $this->manager->getConnection()->executeQuery(
587
                    'UPDATE s_plugin_connect_items
588
                    SET export_status = ?
589
                    WHERE revision IS NULL
590
                    AND ( export_status = ? OR export_status = ? )',
591
                    [$statusSynced, $statusInsert, $statusUpdate]
592
                );
593
594
                $this->manager->getConnection()->executeQuery(
595
                    'UPDATE s_plugin_connect_items
596
                    SET export_status = ?
597
                    WHERE revision IS NULL
598
                    AND export_status = ?',
599
                    [null, $statusDelete]
600
                );
601
            }
602
603
604
            /** @var \Shopware\Connect\Struct\Change $change */
605
            foreach ($changes as $change) {
606
                if (!$change instanceof Insert && !$change instanceof Update && !$change instanceof Availability) {
607
                    continue;
608
                }
609
610
                $this->manager->getConnection()->executeQuery(
611
                    'UPDATE s_plugin_connect_items
612
                    SET revision = ?
613
                    WHERE source_id = ? AND shop_id IS NULL',
614
                    [$change->revision, $change->sourceId]
615
                );
616
            }
617
618
            $this->manager->getConnection()->commit();
619
        } catch (\Exception $e) {
620
            $this->manager->getConnection()->rollBack();
621
        }
622
623
        try {
624
            $this->markStreamsAsSynced();
625
            $this->markStreamsAsNotExported();
626
        } catch (\Exception $e) {
627
            $this->logger->write(
628
                true,
629
                sprintf('Failed to mark streams as synced! Message: "%s". Trace: "%s"', $e->getMessage(), $e->getTraceAsString()),
630
                null
631
            );
632
        }
633
    }
634
635 View Code Duplication
    private function markStreamsAsNotExported()
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...
636
    {
637
        $streamIds = $this->manager->getConnection()->executeQuery(
638
            'SELECT pcs.stream_id as streamId
639
             FROM s_plugin_connect_streams as pcs
640
             WHERE export_status = ?',
641
            [ProductStreamService::STATUS_DELETE]
642
        )->fetchAll();
643
644
        foreach ($streamIds as $stream) {
645
            $streamId = $stream['streamId'];
646
647
            $notDeleted = $this->manager->getConnection()->executeQuery(
648
                'SELECT pss.id
649
                 FROM s_product_streams_selection as pss
650
                 JOIN s_plugin_connect_items as pci
651
                 ON pss.article_id = pci.article_id
652
                 WHERE pss.stream_id = ?
653
                 AND pci.export_status != ?',
654
                [$streamId, null]
655
            )->fetchAll();
656
657
            if (count($notDeleted) === 0) {
658
                $this->manager->getConnection()->executeQuery(
659
                    'UPDATE s_plugin_connect_streams
660
                     SET export_status = ?
661
                     WHERE stream_id = ?',
662
                    [null, $streamId]
663
                );
664
            }
665
        }
666
    }
667
668 View Code Duplication
    private function markStreamsAsSynced()
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...
669
    {
670
        $streamIds = $this->manager->getConnection()->executeQuery(
671
            'SELECT pcs.stream_id as streamId
672
             FROM s_plugin_connect_streams as pcs
673
             WHERE export_status = ?',
674
            [ProductStreamService::STATUS_EXPORT]
675
        )->fetchAll();
676
677
        foreach ($streamIds as $stream) {
678
            $streamId = $stream['streamId'];
679
680
            $notExported = $this->manager->getConnection()->executeQuery(
681
                'SELECT pss.id
682
                 FROM s_product_streams_selection as pss
683
                 JOIN s_plugin_connect_items as pci
684
                 ON pss.article_id = pci.article_id
685
                 WHERE pss.stream_id = ?
686
                 AND pci.export_status != ?',
687
                [$streamId, Attribute::STATUS_SYNCED]
688
            )->fetchAll();
689
690
            if (count($notExported) === 0) {
691
                $this->manager->getConnection()->executeQuery(
692
                    'UPDATE s_plugin_connect_streams
693
                     SET export_status = ?
694
                     WHERE stream_id = ?',
695
                    [ProductStreamService::STATUS_SYNCED, $streamId]
696
                );
697
            }
698
        }
699
    }
700
701
    /**
702
     * @param Address $address
703
     */
704
    private function validateBilling(Address $address)
705
    {
706
        if (!$address->email) {
707
            throw new \RuntimeException('Billing address should contain email');
708
        }
709
710
        if (!$address->firstName) {
711
            throw new \RuntimeException('Billing address should contain first name');
712
        }
713
714
        if (!$address->surName) {
715
            throw new \RuntimeException('Billing address should contain last name');
716
        }
717
718
        if (!$address->zip) {
719
            throw new \RuntimeException('Billing address should contain zip');
720
        }
721
722
        if (!$address->city) {
723
            throw new \RuntimeException('Billing address should contain city');
724
        }
725
726
        if (!$address->phone) {
727
            throw new \RuntimeException('Billing address should contain phone');
728
        }
729
    }
730
}
731