Completed
Pull Request — master (#473)
by Sebastian
05:41
created

BasketHelper::buildProductsArray()   C

Complexity

Conditions 7
Paths 6

Size

Total Lines 35
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 35
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 21
nc 6
nop 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\Components;
9
10
use Shopware\Connect\Gateway\PDO;
11
use Shopware\Connect\Struct\CheckResult;
12
use Shopware\Connect\SDK;
13
use Shopware\Connect\Struct\Message;
14
use Shopware\Connect\Struct\Product;
15
16
/**
17
 * Handles the basket manipulation. Most of it is done by modifying the template variables shown to the user.
18
 * Once we have new basket and order core classes, this should be refactored.
19
 *
20
 * Class BasketHelper
21
 * @package ShopwarePlugins\Connect\Components
22
 */
23
class BasketHelper
24
{
25
    const REMOTE_SHIPPING = 'remote';
26
27
    /**
28
     * The basket array decorated by this class
29
     * @var array
30
     */
31
    protected $basket;
32
33
    /**
34
     * Array of connect product structs
35
     * @var array
36
     */
37
    protected $connectProducts = [];
38
39
    /**
40
     * connect content as formated by shopware
41
     *
42
     * @var array
43
     */
44
    protected $connectContent = [];
45
46
    /**
47
     * Array of connect shops affected by this basket
48
     *
49
     * @var array
50
     */
51
    protected $connectShops = [];
52
53
    /**
54
     * @var \Shopware\Connect\Struct\CheckResult
55
     */
56
    protected $checkResult;
57
58
    /**
59
     * The original shopware shipping costs
60
     *
61
     * @var float
62
     */
63
    protected $originalShippingCosts = 0;
64
65
    /**
66
     * Should there be a connect hint in the template
67
     *
68
     * @var bool
69
     */
70
    protected $showCheckoutShopInfo;
71
72
    /**
73
     * @var \Shopware\Connect\SDK
74
     */
75
    protected $sdk;
76
77
    /**
78
     * @var \Enlight_Components_Db_Adapter_Pdo_Mysql
79
     */
80
    protected $database;
81
82
    /**
83
     * @var Helper
84
     */
85
    protected $helper;
86
87
    /**
88
     * @var \Shopware\Connect\Gateway\PDO
89
     */
90
    protected $connectGateway;
91
92
    /**
93
     * Indicates if the basket has only connect products or not
94
     *
95
     * @var bool
96
     */
97
    protected $onlyConnectProducts = false;
98
99
    /**
100
     * @param \Enlight_Components_Db_Adapter_Pdo_Mysql $database
101
     * @param \Shopware\Connect\SDK $sdk
102
     * @param Helper $helper
103
     * @param $showCheckoutShopInfo
104
     */
105
    public function __construct(
106
        \Enlight_Components_Db_Adapter_Pdo_Mysql $database,
107
        SDK $sdk,
108
        Helper $helper,
109
        PDO $connectGateway,
110
        $showCheckoutShopInfo
111
    ) {
112
        $this->database = $database;
113
        $this->sdk = $sdk;
114
        $this->helper = $helper;
115
        $this->connectGateway = $connectGateway;
116
        $this->showCheckoutShopInfo = $showCheckoutShopInfo;
117
    }
118
119
    /**
120
     * Prepare the basket for connect
121
     *
122
     * @return void
123
     */
124
    public function prepareBasketForConnect()
125
    {
126
        $this->buildProductsArray();
127
        $this->buildShopsArray();
128
    }
129
130
    /**
131
     * Build array of connect products. This will remove connect products from the 'content' array
132
     */
133
    protected function buildProductsArray()
134
    {
135
        $this->connectProducts = [];
136
        $this->connectContent = [];
137
138
        $this->basket['contentOrg'] = $this->basket['content'];
139
140
        foreach ($this->basket['content'] as $key => &$row) {
141
            if (!empty($row['mode'])) {
142
                continue;
143
            }
144
145
            $articleDetailId = $row['additional_details']['articleDetailsID'];
146
            if ($this->helper->isRemoteArticleDetailDBAL($articleDetailId) === false) {
147
                continue;
148
            }
149
150
            $shopProductId = $this->helper->getShopProductId($articleDetailId);
151
            $products = $this->getHelper()->getRemoteProducts([$shopProductId->sourceId], $shopProductId->shopId);
152
            if (empty($products)) {
153
                continue;
154
            }
155
            $product = reset($products);
156
            if ($product === null || $product->shopId === null) {
157
                continue;
158
            }
159
            $row['connectShopId'] = $product->shopId;
160
            $this->connectProducts[$product->shopId][$product->sourceId] = $product;
161
            $this->connectContent[$product->shopId][$product->sourceId] = $row;
162
163
            //if($actionName == 'cart') {
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
164
            unset($this->basket['content'][$key]);
165
            //}
166
        }
167
    }
168
169
    /**
170
     * Build array of connect remote shops
171
     */
172
    protected function buildShopsArray()
173
    {
174
        $this->connectShops = [];
175
176
        $this->basket['content'] = array_values($this->basket['content']);
177
        foreach ($this->connectContent as $shopId => $items) {
178
            $this->connectShops[$shopId] = $this->getSdk()->getShop($shopId);
179
        }
180
    }
181
182
    /**
183
     * Returns the quantity of a given product in the sw basket
184
     *
185
     * @param \Shopware\Connect\Struct\Product $product
186
     * @return mixed
187
     */
188
    public function getQuantityForProduct(Product $product)
189
    {
190
        if (isset($this->connectContent[$product->shopId]) &&
191
            isset($this->connectContent[$product->shopId][$product->sourceId])
192
        ) {
193
            return (int) $this->connectContent[$product->shopId][$product->sourceId]['quantity'];
194
        } elseif (isset($this->basket['content'][$product->sourceId])) {
195
            return (int) $this->basket['content'][$product->sourceId]['quantity'];
196
        }
197
198
        return 1;
199
    }
200
201
    /**
202
     * This method will check, if any *real* products from the local shop are in the basket. If this is not the
203
     * case, this method will:
204
     *
205
     * - set the first connect shop as content of the default basket ($basket['content'])
206
     * - remove any surcharges, vouchers and  discount from the original basket(!)
207
     *
208
     * @return bool|mixed
209
     */
210
    public function fixBasket()
211
    {
212
        // Filter out basket items which cannot be purchased on their own
213
        $content = array_filter($this->basket['content'], function ($item) {
214
            switch ((int) $item['modus']) {
215
                    case 0: // Default products
216
                    case 1: // Premium products
217
                        return true;
218
                    default:
219
                        return false;
220
                }
221
        });
222
223
        // If only connect products are in the basket, do the basket fix
224
        if (empty($content)) {
225
            $this->onlyConnectProducts = true;
226
227
            $this->removeNonProductsFromBasket();
228
229
            $connectContent = $this->getConnectContent();
230
            if ($this->customerHasToPayLocalShipping($connectContent) === false) {
231
                $this->basket = $this->removeDefaultShipping($this->basket);
232
            }
233
234
            // Make the first connect shop the default basket-content
235
            reset($connectContent);
236
            $shopId = current(array_keys($connectContent));
237
            $this->basket['content'] = $connectContent[$shopId];
238
            unset($this->connectContent[$shopId]);
239
240
            return $shopId;
241
        }
242
243
        return false;
244
    }
245
246
    /**
247
     * Verifies that some of suppliers as shippingCosts type
248
     * different from "remote". Then endcustomer must pay
249
     * merchant shipping costs
250
     *
251
     * @param array $connectContent
252
     * @return bool
253
     */
254
    private function customerHasToPayLocalShipping(array $connectContent)
255
    {
256
        $useLocalShipping = false;
257
258
        foreach (array_keys($connectContent) as $shopId) {
259
            $shopConfiguration = $this->connectGateway->getShopConfiguration($shopId);
260
            if ($shopConfiguration === null) {
261
                continue;
262
            }
263
264
            if ($shopConfiguration->importedProductsShippingCostType != self::REMOTE_SHIPPING) {
265
                $useLocalShipping = true;
266
                break;
267
            }
268
        }
269
270
        return $useLocalShipping;
271
    }
272
273
    /**
274
     * Remove shipping costs from given basket
275
     *
276
     * @param array $basket
277
     * @return array
278
     */
279
    private function removeDefaultShipping(array $basket)
280
    {
281
        $basket['AmountNumeric'] -= $basket['sShippingcosts'];
282
        $basket['AmountNetNumeric'] -= $basket['sShippingcostsNet'];
283
284
        $basketHasTax = $this->hasTax();
285
        if (!empty($this->basket['sAmountWithTax'])) {
286
            if ($basketHasTax) {
287
                $this->basket['sAmountWithTax'] -= $basket['sShippingcosts'];
288
            } else {
289
                $this->basket['sAmountWithTax'] -= $basket['sShippingcostsNet'];
290
            }
291
        }
292
293
        if ($basketHasTax) {
294
            $basket['sAmount'] -= $basket['sShippingcosts'];
295
        } else {
296
            $basket['sAmount'] -= $basket['sShippingcostsNet'];
297
        }
298
299
        $basket['sShippingcosts'] = 0;
300
        $basket['sShippingcostsNet'] = 0;
301
        $basket['sShippingcostsWithTax'] = 0;
302
303
        return $basket;
304
    }
305
306
    /**
307
     * Removes non-connect products from the database and fixes the basket variables
308
     */
309
    protected function removeNonProductsFromBasket()
310
    {
311
        $removeItems = [
312
            'ids' => [],
313
            'price' => 0,
314
            'netprice' => 0,
315
            'sessionId' => null
316
        ];
317
318
        // Build array of ids and amount to fix the basket later
319
        foreach ($this->basket['content'] as  $key => $product) {
320
            $removeItems['ids'][] = $product['id'];
321
            $removeItems['price'] += $product['price'] * $product['quantity'];
322
            $removeItems['amountWithTax'] += $product['amountWithTax'] * $product['quantity'];
323
            $removeItems['netprice'] += $product['netprice'] * $product['quantity'];
324
            $removeItems['tax'] += str_replace(',', '.', $product['tax']) * $product['quantity'];
325
            $removeItems['sessionId'] = $product['sessionID'];
326
327
            // Remove surcharge, cannot be deleted with SQL
328
            if ($product['modus'] == 4) {
329
                unset($this->basket['content'][$key]);
330
            }
331
        }
332
333
        if (empty($removeItems['ids'])) {
334
            return;
335
        }
336
337
        // Fix basket prices
338
        $this->basket['AmountNumeric'] -= $removeItems['price'];
339
        $this->basket['AmountNetNumeric'] -= $removeItems['netprice'];
340
        $this->basket['sAmount'] -= $removeItems['price'];
341
        $this->basket['Amount'] = str_replace(',', '.', $this->basket['Amount']) - $removeItems['price'];
342
343
        $this->basket['sAmountTax'] -= $removeItems['tax'];
344
        if (!empty($this->basket['sAmountWithTax'])) {
345
            if ($this->hasTax()) {
346
                $this->basket['sAmountWithTax'] -= $removeItems['price'];
347
            } else {
348
                $this->basket['sAmountWithTax'] -= $removeItems['amountWithTax'];
349
                $this->basket['AmountWithTaxNumeric'] -= $removeItems['amountWithTax'];
350
                $this->basket['AmountWithTax'] = $this->basket['AmountWithTaxNumeric'];
351
                $this->basket['amountnet'] = $this->basket['amount'];
352
            }
353
        }
354
355
        // Remove items from basket
356
        $this->getDatabase()->query(
357
            'DELETE FROM s_order_basket WHERE sessionID = ? and id IN (?)',
358
            [
359
                $removeItems['sessionId'],
360
                implode(',', $removeItems['ids'])
361
            ]
362
        );
363
364
        // Filter out basket items - surcharge
365
        $this->basket['contentOrg'] = array_filter($this->basket['contentOrg'], function ($item) {
366
            switch ((int) $item['modus']) {
367
                case 4: // Surcharge
368
                    return false;
369
                default:
370
                    return true;
371
            }
372
        });
373
    }
374
375
    /**
376
     * @todo: This function is basically a copy of the same function in Controllers/Frontend/Checkout.
377
     * As that function cannot be called, I copied it for the time being - this should be refactored
378
     *
379
     * @param  $basket array returned from this->getBasket
380
     * @return array
381
     */
382
    public function getTaxRates($basket)
383
    {
384
        $result = [];
385
386
        // The original method also calculates the tax rates of the shipping costs - this
387
        // is done in a separate methode here
388
389
        if (empty($basket['content'])) {
390
            ksort($result, SORT_NUMERIC);
391
392
            return $result;
393
        }
394
395
        foreach ($basket['content'] as $item) {
396
            if (!empty($item['tax_rate'])) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
397
            } elseif (!empty($item['taxPercent'])) {
398
                $item['tax_rate'] = $item['taxPercent'];
399
            } elseif ($item['modus'] == 2) {
400
                // Ticket 4842 - dynamic tax-rates
401
                $resultVoucherTaxMode = Shopware()->Db()->fetchOne(
402
                    'SELECT taxconfig FROM s_emarketing_vouchers WHERE ordercode=?',
403
                    [$item['ordernumber']]
404
                );
405
                // Old behaviour
406
                if (empty($resultVoucherTaxMode) || $resultVoucherTaxMode == 'default') {
407
                    $tax = Shopware()->Config()->get('sVOUCHERTAX');
408
                } elseif ($resultVoucherTaxMode == 'auto') {
409
                    // Automatically determinate tax
410
                    $tax = Shopware()->Modules()->Basket()->getMaxTax();
411
                } elseif ($resultVoucherTaxMode == 'none') {
412
                    // No tax
413
                    $tax = '0';
414
                } elseif (intval($resultVoucherTaxMode)) {
415
                    // Fix defined tax
416
                    $tax = Shopware()->Db()->fetchOne(
417
                        'SELECT tax FROM s_core_tax WHERE id = ?',
418
                        [$resultVoucherTaxMode]
419
                    );
420
                }
421
                $item['tax_rate'] = $tax;
0 ignored issues
show
Bug introduced by
The variable $tax does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
422
            } else {
423
                // Ticket 4842 - dynamic tax-rates
424
                $taxAutoMode = Shopware()->Config()->get('sTAXAUTOMODE');
425
                if (!empty($taxAutoMode)) {
426
                    $tax = Shopware()->Modules()->Basket()->getMaxTax();
427
                } else {
428
                    $tax = Shopware()->Config()->get('sDISCOUNTTAX');
429
                }
430
                $item['tax_rate'] = $tax;
431
            }
432
433
            // Ignore 0 % tax
434
            if (empty($item['tax_rate']) || empty($item['tax'])) {
435
                continue;
436
            }
437
            $taxKey = number_format(floatval($item['tax_rate']), 2);
438
            $result[$taxKey] += str_replace(',', '.', $item['tax']);
439
        }
440
441
        ksort($result, SORT_NUMERIC);
442
443
        return $result;
444
    }
445
446
    /**
447
     * Returns an array of tax positions in the same way, as shopware does in the sTaxRates.
448
     * This will only take connect products returned by getConnectContent() into account,
449
     * so that connect positions moved into basket['content'] earlier are not calculated twice.
450
     *
451
     * @return array
452
     */
453
    public function getConnectTaxRates()
454
    {
455
        $taxes = [];
456
457
        foreach ($this->getConnectContent() as $shopId => $products) {
458
            foreach ($products as $product) {
459
                $vat = (string) number_format($product['tax_rate'], 2);
460
                if (!isset($taxes[$vat])) {
461
                    $taxes[$vat] = 0;
462
                }
463
464
                if ($this->hasTax()) {
465
                    $taxes[$vat] += $product['priceNumeric'] - $product['netprice'];
466
                } else {
467
                    $taxes[$vat] += $product['amountWithTax'] - ($product['netprice'] * $product['quantity']);
468
                }
469
            }
470
        }
471
472
        return $taxes;
473
    }
474
475
    /**
476
     * Will merge/add various arrays of "sTaxRates" like arrays into one array
477
     *
478
     * @param array $taxRates
479
     * @return array
480
     */
481
    public function getMergedTaxRates(array $taxRates)
482
    {
483
        $result = [];
484
485
        foreach ($taxRates as $taxRate) {
486
            foreach ($taxRate as $vat => $amount) {
487
                if (!isset($result[$vat])) {
488
                    $result[$vat] = 0;
489
                }
490
                $result[$vat] += $amount;
491
            }
492
        }
493
494
        return $result;
495
    }
496
497
    /**
498
     * Increase the basket's shipping costs and amount by the total value of connect shipping costs
499
     *
500
     * @param \Shopware\Connect\Struct\CheckResult $checkResult
501
     */
502
    public function recalculate(CheckResult $checkResult)
503
    {
504
        $this->checkResult = $checkResult;
505
        $this->basket['sAmount'] = number_format($this->basket['sAmount'], 2, '.', '');
506
507
        $shippingCostsNet = 0;
508
        $shippingCostsWithTax = 0;
509
510
        /** @var \Shopware\Connect\Struct\Shipping $shipping */
511
        foreach ($this->checkResult->shippingCosts as $shipping) {
512
            $shopConfiguration = $this->connectGateway->getShopConfiguration($shipping->shopId);
513
            if ($shopConfiguration->importedProductsShippingCostType == self::REMOTE_SHIPPING) {
514
                $shippingCostsNet += $shipping->shippingCosts;
515
                $shippingCostsWithTax += $shipping->grossShippingCosts;
516
            }
517
        }
518
        $shippingCostsNet = number_format($shippingCostsNet, 2, '.', '');
519
        $shippingCostsWithTax = number_format($shippingCostsWithTax, 2, '.', '');
520
521
        $basketHasTax = $this->hasTax();
522
523
        // Set the shipping cost tax rate for shopware
524
525
        $this->setOriginalShippingCosts($this->basket['sShippingcosts']);
526
527
        // Update shipping costs
528
        if ($basketHasTax) {
529
            $this->basket['sShippingcosts'] += $shippingCostsWithTax;
530
        } else {
531
            $this->basket['sShippingcosts'] += $shippingCostsNet;
532
        }
533
        $this->basket['sShippingcostsNet'] += $shippingCostsNet;
534
        $this->basket['sShippingcostsWithTax'] += $shippingCostsWithTax;
535
536
        $this->basket['AmountNetNumeric'] += $shippingCostsNet;
537
538
        if (!empty($this->basket['sAmountWithTax'])) {
539
            if ($basketHasTax) {
540
                $this->basket['sAmountWithTax'] += $this->basket['sShippingcostsWithTax'];
541
            } else {
542
                $this->basket['sAmountWithTax'] += $shippingCostsWithTax;
543
            }
544
        }
545
546
        if ($basketHasTax) {
547
            $this->basket['sAmount'] += $shippingCostsWithTax;
548
        } else {
549
            $this->basket['sAmount'] += $shippingCostsNet;
550
        }
551
552
        $this->basket['sAmountTax'] += $this->basket['sShippingcostsWithTax'] - $shippingCostsNet;
553
554
        // Core workaround: Shopware tries to re-calculate the shipping tax rate from the net price
555
        // \Shopware_Models_Document_Order::processOrder
556
        // Therefore we need to round the net price
557
        $this->basket['sShippingcostsNet'] = round($this->basket['sShippingcostsNet'], 2);
558
559
560
        // Recalculate the tax rates
561
        $this->basket['sTaxRates'] = $this->getMergedTaxRates(
562
            [
563
                $this->getTaxRates($this->basket),
564
                $this->getConnectTaxRates(),
565
                $this->getShippingCostsTaxRates()
566
            ]
567
        );
568
569
        //@todo:stefan Check for better solution
570
        $this->basket['AmountWithTaxNumeric'] = $this->basket['sAmountWithTax'];
571
        $this->basket['AmountNumeric'] = $this->basket['sAmount'];
572
    }
573
574
    /**
575
     * Returns the tax rate of the shipping costs and also sets the the net shipping cost amount(!)
576
     */
577
    public function getShippingCostsTaxRates()
578
    {
579
        $taxAmount = $this->basket['sShippingcostsWithTax'] - $this->basket['sShippingcostsNet'];
580
581
        $taxRate = number_format($this->getMaxTaxRate(), 2, '.', '');
582
        $this->basket['sShippingcostsNet'] = $this->basket['sShippingcostsWithTax'] / (($taxRate/100)+1);
583
584
        return [
585
            (string) $taxRate => $taxAmount
586
        ];
587
    }
588
589
    /**
590
     * Get the highest tax rate from basket - currently only this is supported by SW
591
     *
592
     * @return int
593
     */
594
    public function getMaxTaxRate()
595
    {
596
        $taxRate = 0;
597
        foreach ($this->getConnectContent() as $shopId => $products) {
598
            foreach ($products as $product) {
599
                if ($product['tax_rate'] > $taxRate) {
600
                    $taxRate = $product['tax_rate'];
601
                }
602
            }
603
        }
604
605
        foreach ($this->basket['content'] as $product) {
606
            if ($product['tax_rate'] > $taxRate) {
607
                $taxRate = $product['tax_rate'];
608
            }
609
        }
610
611
        return $taxRate;
612
    }
613
614
    /**
615
     * Return array of variables which need to be available in the default template
616
     *
617
     * @return array
618
     */
619
    public function getDefaultTemplateVariables()
620
    {
621
        return [
622
            'sBasket' => $this->basket,
623
            'sShippingcosts' => $this->basket['sShippingcosts'],
624
            'sAmount' => $this->basket['sAmount'],
625
            'sAmountWithTax' => $this->basket['sAmountWithTax'],
626
            'sAmountNet' => $this->basket['AmountNetNumeric']
627
        ];
628
    }
629
630
    /**
631
     * Return array of connect specific template variables
632
     *
633
     * @param $connectMessages array Messages to show
634
     * @return array
635
     */
636
    public function getConnectTemplateVariables(array $connectMessages)
637
    {
638
        $snippets = Shopware()->Snippets()->getNamespace('frontend/checkout/error_messages');
639
640
        /** @var Message $message */
641
        foreach ($connectMessages as $message) {
642
            if ($message->message == 'Availability of product %product changed to %availability.') {
643
644
                $this->guessProductTitle($message);
645
646
                if ($message->values['availability'] == 0) {
647
                    $message->message = $snippets->get(
648
                        'connect_product_out_of_stock_message',
649
                        'Das Product "%ptitle" in Ihrer Bestellung ist aktuell nicht lieferbar, bitte entfernen Sie das Produkt um fortzufahren.'
650
                    );
651
                } else {
652
                    $message->message = $snippets->get(
653
                        'connect_product_lower_stock_message',
654
                        'Der Lagerbestand von Produkt "%ptitle" hat sich auf %availability geändert.'
655
                    );
656
                }
657
            }
658
        }
659
660
        return [
661
            'connectContent' => $this->getConnectContent(),
662
            'connectShops' => $this->getConnectShops(),
663
            'connectMessages' => $connectMessages,
664
            'connectShippingCosts' => $this->getConnectGrossShippingCosts(),
665
            'connectShippingCostsOrg' => $this->getOriginalShippingCosts(),
666
            'connectShopInfo' => $this->showCheckoutShopInfo,
667
            'addBaseShop' => $this->onlyConnectProducts ? 0 : 1,
668
        ];
669
    }
670
671
    private function guessProductTitle(Message $message)
672
    {
673
        if (isset($message->values['shopId'])) {
674
            $product = $this->getConnectProducts()[$message->values['shopId']][$message->values['product']];
675
            $message->values['ptitle'] = $product->title;
676
            return;
677
        }
678
679
        //sdk version < v2.0.12
680
        foreach ($this->getConnectProducts() as $supplierArray) {
681
            foreach ($supplierArray as $key => $product) {
682
                if ($key == $message->values['product'] && $product->availability == 0 )
683
                    $message->values['ptitle'] = $product->title;
684
                return;
685
            }
686
        }
687
    }
688
689
    /**
690
     * Modifies a given OrderVariables ArrayObject
691
     *
692
     * @param $variables \ArrayObject
693
     * @return \ArrayObject
694
     */
695
    public function getOrderVariablesForSession($variables)
696
    {
697
        // Get a copy of the basket array in order to not mess up the state of the basket array
698
        $basket = $this->basket;
699
        $newVariables = $this->getDefaultTemplateVariables();
700
701
        // We need the manipulated content as the order is created from the session
702
        $basket['content'] = $basket['contentOrg'];
703
        unset($basket['contentOrg']);
704
705
706
        // Replace the original session array with the new one
707
        $variables->exchangeArray(array_merge(
708
            $variables->getArrayCopy(),
709
            $newVariables,
710
            ['sBasket' => $basket]
711
        ));
712
713
        return $variables;
714
    }
715
716
    /**
717
     * Find all percentaged vouchers for a given individual code
718
     *
719
     * @param $voucherCode
720
     * @return mixed
721
     */
722 View Code Duplication
    public function findPercentagedIndividualVouchers($voucherCode)
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...
723
    {
724
        $builder = Shopware()->Models()->createQueryBuilder();
725
726
        $builder->select('voucher')
727
            ->from('Shopware\Models\Voucher\Voucher', 'voucher')
728
            ->innerJoin('voucher.codes', 'codes', 'WITH', 'codes.code LIKE :voucherCode')
729
            ->where('voucher.percental = true')
730
            ->setParameter('voucherCode', $voucherCode);
731
732
        return $builder->getQuery()->getResult();
733
    }
734
735
    /**
736
     * Find all vouchers matching the code
737
     *
738
     * @param $voucherCode
739
     * @return mixed
740
     */
741 View Code Duplication
    public function findPercentagedVouchers($voucherCode)
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...
742
    {
743
        $builder = Shopware()->Models()->createQueryBuilder();
744
745
        $builder->select('voucher')
746
            ->from('Shopware\Models\Voucher\Voucher', 'voucher')
747
            ->where('voucher.voucherCode LIKE :voucherCode')
748
            ->andWhere('voucher.percental = true')
749
            ->setParameter('voucherCode', $voucherCode);
750
751
        return $builder->getQuery()->getResult();
752
    }
753
754
    /**
755
     * @return \Shopware\Connect\SDk
756
     */
757
    public function getSdk()
758
    {
759
        return $this->sdk;
760
    }
761
762
    /**
763
     * @return Helper
764
     */
765
    public function getHelper()
766
    {
767
        return $this->helper;
768
    }
769
770
    /**
771
     * @param mixed $basket
772
     */
773
    public function setBasket($basket)
774
    {
775
        $this->basket = $basket;
0 ignored issues
show
Documentation Bug introduced by
It seems like $basket of type * is incompatible with the declared type array of property $basket.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
776
        $this->prepareBasketForConnect();
777
    }
778
779
    /**
780
     * @return mixed
781
     */
782
    public function getBasket()
783
    {
784
        return $this->basket;
785
    }
786
787
    /**
788
     * @param array $connectContent
789
     */
790
    public function setConnectContent($connectContent)
791
    {
792
        $this->connectContent = $connectContent;
793
    }
794
795
    /**
796
     * @return array
797
     */
798
    public function getConnectContent()
799
    {
800
        return $this->connectContent;
801
    }
802
803
    /**
804
     * @param array $connectProducts
805
     */
806
    public function setConnectProducts($connectProducts)
807
    {
808
        $this->connectProducts = $connectProducts;
809
    }
810
811
    /**
812
     * @return array
813
     */
814
    public function getConnectProducts()
815
    {
816
        return $this->connectProducts;
817
    }
818
819
    /**
820
     * @param array $connectShops
821
     */
822
    public function setConnectShops($connectShops)
823
    {
824
        $this->connectShops = $connectShops;
825
    }
826
827
    /**
828
     * @return array
829
     */
830
    public function getConnectShops()
831
    {
832
        return $this->connectShops;
833
    }
834
835
    /**
836
     * @return array
837
     */
838
    public function getConnectGrossShippingCosts()
839
    {
840
        $result = [];
841
        if (!$this->checkResult instanceof CheckResult) {
842
            return $result;
843
        }
844
845
        foreach ($this->checkResult->shippingCosts as $shipping) {
846
            if ($this->hasTax()) {
847
                $result[$shipping->shopId] = $shipping->grossShippingCosts;
848
            } else {
849
                $result[$shipping->shopId] = $shipping->shippingCosts;
850
            }
851
        }
852
853
        return $result;
854
    }
855
856
    /**
857
     * @param mixed $originalShippingCosts
858
     */
859
    public function setOriginalShippingCosts($originalShippingCosts)
860
    {
861
        $this->originalShippingCosts = $originalShippingCosts;
862
    }
863
864
    /**
865
     * @return mixed
866
     */
867
    public function getOriginalShippingCosts()
868
    {
869
        return $this->originalShippingCosts;
870
    }
871
872
    /**
873
     * @param \Enlight_Components_Db_Adapter_Pdo_Mysql $database
874
     */
875
    public function setDatabase($database)
876
    {
877
        $this->database = $database;
878
    }
879
880
    /**
881
     * @return \Enlight_Components_Db_Adapter_Pdo_Mysql
882
     */
883
    public function getDatabase()
884
    {
885
        return $this->database;
886
    }
887
888
    /**
889
     * Returns "Gross price displayed in frontend" value
890
     * @return bool
891
     */
892
    protected function hasTax()
893
    {
894
        $customerGroup = Shopware()->Session()->sUserGroup;
895
        if (!$customerGroup) {
896
            $customerGroup = 'EK';
897
        }
898
899
        $repository = Shopware()->Models()->getRepository('Shopware\Models\Customer\Group');
900
        $groupModel = $repository->findOneBy(['key' => $customerGroup]);
901
902
        return $groupModel->getTax();
903
    }
904
905
    /**
906
     * @return \Shopware\Connect\Struct\CheckResult
907
     */
908
    public function getCheckResult()
909
    {
910
        return $this->checkResult ?: new CheckResult();
911
    }
912
913
    /**
914
     * @param \Shopware\Connect\Struct\CheckResult $checkResult
915
     */
916
    public function setCheckResult(CheckResult $checkResult)
917
    {
918
        $this->checkResult = $checkResult;
919
    }
920
}
921