Completed
Push — master ( f08ce5...e1afd8 )
by Sven
33s
created

BasketHelper::getConfig()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * (c) shopware AG <[email protected]>
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
8
namespace ShopwarePlugins\Connect\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
            $connectContent = $this->getConnectContent();
228
            if ($this->customerHasToPayLocalShipping($connectContent) === false) {
229
                $this->basket = $this->removeDefaultShipping($this->basket);
230
            }
231
232
            reset($connectContent);
233
            $shopId = current(array_keys($connectContent));
234
235
            $config = $this->getConfig();
236
            if ($config->getConfig('removeBasketAdditions'))
237
            {
238
                $this->removeNonProductsFromBasket();
239
                // Make the first connect shop the default basket-content
240
                $this->basket['content'] = $connectContent[$shopId];
241
                unset($this->connectContent[$shopId]);
242
            }
243
            
244
            return $shopId;
245
        }
246
247
        return false;
248
    }
249
250
    /**
251
     * Verifies that some of suppliers as shippingCosts type
252
     * different from "remote". Then endcustomer must pay
253
     * merchant shipping costs
254
     *
255
     * @param array $connectContent
256
     * @return bool
257
     */
258
    private function customerHasToPayLocalShipping(array $connectContent)
259
    {
260
        $useLocalShipping = false;
261
262
        foreach (array_keys($connectContent) as $shopId) {
263
            $shopConfiguration = $this->connectGateway->getShopConfiguration($shopId);
264
            if ($shopConfiguration === null) {
265
                continue;
266
            }
267
268
            if ($shopConfiguration->importedProductsShippingCostType != self::REMOTE_SHIPPING) {
269
                $useLocalShipping = true;
270
                break;
271
            }
272
        }
273
274
        return $useLocalShipping;
275
    }
276
277
    /**
278
     * Remove shipping costs from given basket
279
     *
280
     * @param array $basket
281
     * @return array
282
     */
283
    private function removeDefaultShipping(array $basket)
284
    {
285
        $basket['AmountNumeric'] -= $basket['sShippingcosts'];
286
        $basket['AmountNetNumeric'] -= $basket['sShippingcostsNet'];
287
288
        $basketHasTax = $this->hasTax();
289
        if (!empty($this->basket['sAmountWithTax'])) {
290
            if ($basketHasTax) {
291
                $this->basket['sAmountWithTax'] -= $basket['sShippingcosts'];
292
            } else {
293
                $this->basket['sAmountWithTax'] -= $basket['sShippingcostsNet'];
294
            }
295
        }
296
297
        if ($basketHasTax) {
298
            $basket['sAmount'] -= $basket['sShippingcosts'];
299
        } else {
300
            $basket['sAmount'] -= $basket['sShippingcostsNet'];
301
        }
302
303
        $basket['sShippingcosts'] = 0;
304
        $basket['sShippingcostsNet'] = 0;
305
        $basket['sShippingcostsWithTax'] = 0;
306
307
        return $basket;
308
    }
309
310
    /**
311
     * Removes non-connect products from the database and fixes the basket variables
312
     */
313
    protected function removeNonProductsFromBasket()
314
    {
315
        $removeItems = [
316
            'ids' => [],
317
            'price' => 0,
318
            'netprice' => 0,
319
            'sessionId' => null
320
        ];
321
322
        // Build array of ids and amount to fix the basket later
323
        foreach ($this->basket['content'] as  $key => $product) {
324
            $removeItems['ids'][] = $product['id'];
325
            $removeItems['price'] += $product['price'] * $product['quantity'];
326
            $removeItems['amountWithTax'] += $product['amountWithTax'] * $product['quantity'];
327
            $removeItems['netprice'] += $product['netprice'] * $product['quantity'];
328
            $removeItems['tax'] += str_replace(',', '.', $product['tax']) * $product['quantity'];
329
            $removeItems['sessionId'] = $product['sessionID'];
330
331
            // Remove surcharge, cannot be deleted with SQL
332
            if ($product['modus'] == 4) {
333
                unset($this->basket['content'][$key]);
334
            }
335
        }
336
337
        if (empty($removeItems['ids'])) {
338
            return;
339
        }
340
341
        // Fix basket prices
342
        $this->basket['AmountNumeric'] -= $removeItems['price'];
343
        $this->basket['AmountNetNumeric'] -= $removeItems['netprice'];
344
        $this->basket['sAmount'] -= $removeItems['price'];
345
        $this->basket['Amount'] = str_replace(',', '.', $this->basket['Amount']) - $removeItems['price'];
346
347
        $this->basket['sAmountTax'] -= $removeItems['tax'];
348
        if (!empty($this->basket['sAmountWithTax'])) {
349
            if ($this->hasTax()) {
350
                $this->basket['sAmountWithTax'] -= $removeItems['price'];
351
            } else {
352
                $this->basket['sAmountWithTax'] -= $removeItems['amountWithTax'];
353
                $this->basket['AmountWithTaxNumeric'] -= $removeItems['amountWithTax'];
354
                $this->basket['AmountWithTax'] = $this->basket['AmountWithTaxNumeric'];
355
                $this->basket['amountnet'] = $this->basket['amount'];
356
            }
357
        }
358
359
        // Remove items from basket
360
        $this->getDatabase()->query(
361
            'DELETE FROM s_order_basket WHERE sessionID = ? and id IN (?)',
362
            [
363
                $removeItems['sessionId'],
364
                implode(',', $removeItems['ids'])
365
            ]
366
        );
367
368
        // Filter out basket items - surcharge
369
        $this->basket['contentOrg'] = array_filter($this->basket['contentOrg'], function ($item) {
370
            switch ((int) $item['modus']) {
371
                case 4: // Surcharge
372
                    return false;
373
                default:
374
                    return true;
375
            }
376
        });
377
    }
378
379
    /**
380
     * @todo: This function is basically a copy of the same function in Controllers/Frontend/Checkout.
381
     * As that function cannot be called, I copied it for the time being - this should be refactored
382
     *
383
     * @param  $basket array returned from this->getBasket
384
     * @return array
385
     */
386
    public function getTaxRates($basket)
387
    {
388
        $result = [];
389
390
        // The original method also calculates the tax rates of the shipping costs - this
391
        // is done in a separate methode here
392
393
        if (empty($basket['content'])) {
394
            ksort($result, SORT_NUMERIC);
395
396
            return $result;
397
        }
398
399
        foreach ($basket['content'] as $item) {
400
            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...
401
            } elseif (!empty($item['taxPercent'])) {
402
                $item['tax_rate'] = $item['taxPercent'];
403
            } elseif ($item['modus'] == 2) {
404
                // Ticket 4842 - dynamic tax-rates
405
                $resultVoucherTaxMode = Shopware()->Db()->fetchOne(
406
                    'SELECT taxconfig FROM s_emarketing_vouchers WHERE ordercode=?',
407
                    [$item['ordernumber']]
408
                );
409
                // Old behaviour
410
                if (empty($resultVoucherTaxMode) || $resultVoucherTaxMode == 'default') {
411
                    $tax = Shopware()->Config()->get('sVOUCHERTAX');
412
                } elseif ($resultVoucherTaxMode == 'auto') {
413
                    // Automatically determinate tax
414
                    $tax = Shopware()->Modules()->Basket()->getMaxTax();
415
                } elseif ($resultVoucherTaxMode == 'none') {
416
                    // No tax
417
                    $tax = '0';
418
                } elseif (intval($resultVoucherTaxMode)) {
419
                    // Fix defined tax
420
                    $tax = Shopware()->Db()->fetchOne(
421
                        'SELECT tax FROM s_core_tax WHERE id = ?',
422
                        [$resultVoucherTaxMode]
423
                    );
424
                }
425
                $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...
426
            } else {
427
                // Ticket 4842 - dynamic tax-rates
428
                $taxAutoMode = Shopware()->Config()->get('sTAXAUTOMODE');
429
                if (!empty($taxAutoMode)) {
430
                    $tax = Shopware()->Modules()->Basket()->getMaxTax();
431
                } else {
432
                    $tax = Shopware()->Config()->get('sDISCOUNTTAX');
433
                }
434
                $item['tax_rate'] = $tax;
435
            }
436
437
            // Ignore 0 % tax
438
            if (empty($item['tax_rate']) || empty($item['tax'])) {
439
                continue;
440
            }
441
            $taxKey = number_format(floatval($item['tax_rate']), 2);
442
            $result[$taxKey] += str_replace(',', '.', $item['tax']);
443
        }
444
445
        ksort($result, SORT_NUMERIC);
446
447
        return $result;
448
    }
449
450
    /**
451
     * Returns an array of tax positions in the same way, as shopware does in the sTaxRates.
452
     * This will only take connect products returned by getConnectContent() into account,
453
     * so that connect positions moved into basket['content'] earlier are not calculated twice.
454
     *
455
     * @return array
456
     */
457
    public function getConnectTaxRates()
458
    {
459
        $taxes = [];
460
461
        foreach ($this->getConnectContent() as $shopId => $products) {
462
            foreach ($products as $product) {
463
                $vat = (string) number_format($product['tax_rate'], 2);
464
                if (!isset($taxes[$vat])) {
465
                    $taxes[$vat] = 0;
466
                }
467
468
                if ($this->hasTax()) {
469
                    $taxes[$vat] += $product['priceNumeric'] - $product['netprice'];
470
                } else {
471
                    $taxes[$vat] += $product['amountWithTax'] - ($product['netprice'] * $product['quantity']);
472
                }
473
            }
474
        }
475
476
        return $taxes;
477
    }
478
479
    /**
480
     * Will merge/add various arrays of "sTaxRates" like arrays into one array
481
     *
482
     * @param array $taxRates
483
     * @return array
484
     */
485
    public function getMergedTaxRates(array $taxRates)
486
    {
487
        $result = [];
488
489
        foreach ($taxRates as $taxRate) {
490
            foreach ($taxRate as $vat => $amount) {
491
                if (!isset($result[$vat])) {
492
                    $result[$vat] = 0;
493
                }
494
                $result[$vat] += $amount;
495
            }
496
        }
497
498
        return $result;
499
    }
500
501
    /**
502
     * Increase the basket's shipping costs and amount by the total value of connect shipping costs
503
     *
504
     * @param \Shopware\Connect\Struct\CheckResult $checkResult
505
     */
506
    public function recalculate(CheckResult $checkResult)
507
    {
508
        $this->checkResult = $checkResult;
509
        $this->basket['sAmount'] = number_format($this->basket['sAmount'], 2, '.', '');
510
511
        $shippingCostsNet = 0;
512
        $shippingCostsWithTax = 0;
513
514
        /** @var \Shopware\Connect\Struct\Shipping $shipping */
515
        foreach ($this->checkResult->shippingCosts as $shipping) {
516
            $shopConfiguration = $this->connectGateway->getShopConfiguration($shipping->shopId);
517
            if ($shopConfiguration->importedProductsShippingCostType == self::REMOTE_SHIPPING) {
518
                $shippingCostsNet += $shipping->shippingCosts;
519
                $shippingCostsWithTax += $shipping->grossShippingCosts;
520
            }
521
        }
522
        $shippingCostsNet = number_format($shippingCostsNet, 2, '.', '');
523
        $shippingCostsWithTax = number_format($shippingCostsWithTax, 2, '.', '');
524
525
        $basketHasTax = $this->hasTax();
526
527
        // Set the shipping cost tax rate for shopware
528
529
        $this->setOriginalShippingCosts($this->basket['sShippingcosts']);
530
531
        // Update shipping costs
532
        if ($basketHasTax) {
533
            $this->basket['sShippingcosts'] += $shippingCostsWithTax;
534
        } else {
535
            $this->basket['sShippingcosts'] += $shippingCostsNet;
536
        }
537
        $this->basket['sShippingcostsNet'] += $shippingCostsNet;
538
        $this->basket['sShippingcostsWithTax'] += $shippingCostsWithTax;
539
540
        $this->basket['AmountNetNumeric'] += $shippingCostsNet;
541
542
        if (!empty($this->basket['sAmountWithTax'])) {
543
            if ($basketHasTax) {
544
                $this->basket['sAmountWithTax'] += $this->basket['sShippingcostsWithTax'];
545
            } else {
546
                $this->basket['sAmountWithTax'] += $shippingCostsWithTax;
547
            }
548
        }
549
550
        if ($basketHasTax) {
551
            $this->basket['sAmount'] += $shippingCostsWithTax;
552
        } else {
553
            $this->basket['sAmount'] += $shippingCostsNet;
554
        }
555
556
        $this->basket['sAmountTax'] += $this->basket['sShippingcostsWithTax'] - $shippingCostsNet;
557
558
        // Core workaround: Shopware tries to re-calculate the shipping tax rate from the net price
559
        // \Shopware_Models_Document_Order::processOrder
560
        // Therefore we need to round the net price
561
        $this->basket['sShippingcostsNet'] = round($this->basket['sShippingcostsNet'], 2);
562
563
564
        // Recalculate the tax rates
565
        $this->basket['sTaxRates'] = $this->getMergedTaxRates(
566
            [
567
                $this->getTaxRates($this->basket),
568
                $this->getConnectTaxRates(),
569
                $this->getShippingCostsTaxRates()
570
            ]
571
        );
572
573
        //@todo:stefan Check for better solution
574
        $this->basket['AmountWithTaxNumeric'] = $this->basket['sAmountWithTax'];
575
        $this->basket['AmountNumeric'] = $this->basket['sAmount'];
576
    }
577
578
    /**
579
     * Returns the tax rate of the shipping costs and also sets the the net shipping cost amount(!)
580
     */
581
    public function getShippingCostsTaxRates()
582
    {
583
        $taxAmount = $this->basket['sShippingcostsWithTax'] - $this->basket['sShippingcostsNet'];
584
585
        $taxRate = number_format($this->getMaxTaxRate(), 2, '.', '');
586
        $this->basket['sShippingcostsNet'] = $this->basket['sShippingcostsWithTax'] / (($taxRate/100)+1);
587
588
        return [
589
            (string) $taxRate => $taxAmount
590
        ];
591
    }
592
593
    /**
594
     * Get the highest tax rate from basket - currently only this is supported by SW
595
     *
596
     * @return int
597
     */
598
    public function getMaxTaxRate()
599
    {
600
        $taxRate = 0;
601
        foreach ($this->getConnectContent() as $shopId => $products) {
602
            foreach ($products as $product) {
603
                if ($product['tax_rate'] > $taxRate) {
604
                    $taxRate = $product['tax_rate'];
605
                }
606
            }
607
        }
608
609
        foreach ($this->basket['content'] as $product) {
610
            if ($product['tax_rate'] > $taxRate) {
611
                $taxRate = $product['tax_rate'];
612
            }
613
        }
614
615
        return $taxRate;
616
    }
617
618
    /**
619
     * Return array of variables which need to be available in the default template
620
     *
621
     * @return array
622
     */
623
    public function getDefaultTemplateVariables()
624
    {
625
        return [
626
            'sBasket' => $this->basket,
627
            'sShippingcosts' => $this->basket['sShippingcosts'],
628
            'sAmount' => $this->basket['sAmount'],
629
            'sAmountWithTax' => $this->basket['sAmountWithTax'],
630
            'sAmountNet' => $this->basket['AmountNetNumeric']
631
        ];
632
    }
633
634
    /**
635
     * Return array of connect specific template variables
636
     *
637
     * @param $connectMessages array Messages to show
638
     * @return array
639
     */
640
    public function getConnectTemplateVariables(array $connectMessages)
641
    {
642
        $snippets = Shopware()->Snippets()->getNamespace('frontend/checkout/error_messages');
643
644
        /** @var Message $message */
645
        foreach ($connectMessages as $message) {
646
            if ($message->message == 'Availability of product %product changed to %availability.') {
647
648
                $this->determineProductTitle($message);
649
650
                if ($message->values['availability'] == 0) {
651
                    $message->message = $snippets->get(
652
                        'connect_product_out_of_stock_message_detailed',
653
                        'Das Produkt "%ptitle" in Ihrer Bestellung ist aktuell nicht lieferbar. Bitte entfernen Sie das Produkt um fortzufahren.'
654
                    );
655
                } else {
656
                    $message->message = $snippets->get(
657
                        'connect_product_lower_stock_message_detailed',
658
                        'Der Lagerbestand von Produkt "%ptitle" hat sich auf %availability geändert.'
659
                    );
660
                }
661
            }
662
        }
663
664
        return [
665
            'connectContent' => $this->getConnectContent(),
666
            'connectShops' => $this->getConnectShops(),
667
            'connectMessages' => $connectMessages,
668
            'connectShippingCosts' => $this->getConnectGrossShippingCosts(),
669
            'connectShippingCostsOrg' => $this->getOriginalShippingCosts(),
670
            'connectShopInfo' => $this->showCheckoutShopInfo,
671
            'addBaseShop' => $this->onlyConnectProducts ? 0 : 1,
672
        ];
673
    }
674
675
    private function determineProductTitle(Message $message)
676
    {
677
        if (isset($message->values['shopId'])) {
678
            $product = $this->getConnectProducts()[$message->values['shopId']][$message->values['product']];
679
            $message->values['ptitle'] = $product->title;
680
            return;
681
        }
682
683
        //sdk version < v2.0.12
684
        foreach ($this->getConnectProducts() as $supplierArray) {
685
            foreach ($supplierArray as $product) {
686
                if ($product->sourceId == $message->values['product'] && $product->availability == 0) {
687
                    $message->values['ptitle'] = $product->title;
688
                    return;
689
                }
690
            }
691
        }
692
    }
693
694
    /**
695
     * Modifies a given OrderVariables ArrayObject
696
     *
697
     * @param $variables \ArrayObject
698
     * @return \ArrayObject
699
     */
700
    public function getOrderVariablesForSession($variables)
701
    {
702
        // Get a copy of the basket array in order to not mess up the state of the basket array
703
        $basket = $this->basket;
704
        $newVariables = $this->getDefaultTemplateVariables();
705
706
        // We need the manipulated content as the order is created from the session
707
        $basket['content'] = $basket['contentOrg'];
708
        unset($basket['contentOrg']);
709
710
711
        // Replace the original session array with the new one
712
        $variables->exchangeArray(array_merge(
713
            $variables->getArrayCopy(),
714
            $newVariables,
715
            ['sBasket' => $basket]
716
        ));
717
718
        return $variables;
719
    }
720
721
    /**
722
     * Find all percentaged vouchers for a given individual code
723
     *
724
     * @param $voucherCode
725
     * @return mixed
726
     */
727 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...
728
    {
729
        $builder = Shopware()->Models()->createQueryBuilder();
730
731
        $builder->select('voucher')
732
            ->from('Shopware\Models\Voucher\Voucher', 'voucher')
733
            ->innerJoin('voucher.codes', 'codes', 'WITH', 'codes.code LIKE :voucherCode')
734
            ->where('voucher.percental = true')
735
            ->setParameter('voucherCode', $voucherCode);
736
737
        return $builder->getQuery()->getResult();
738
    }
739
740
    /**
741
     * Find all vouchers matching the code
742
     *
743
     * @param $voucherCode
744
     * @return mixed
745
     */
746 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...
747
    {
748
        $builder = Shopware()->Models()->createQueryBuilder();
749
750
        $builder->select('voucher')
751
            ->from('Shopware\Models\Voucher\Voucher', 'voucher')
752
            ->where('voucher.voucherCode LIKE :voucherCode')
753
            ->andWhere('voucher.percental = true')
754
            ->setParameter('voucherCode', $voucherCode);
755
756
        return $builder->getQuery()->getResult();
757
    }
758
759
    /**
760
     * @return \Shopware\Connect\SDk
761
     */
762
    public function getSdk()
763
    {
764
        return $this->sdk;
765
    }
766
767
    /**
768
     * @return Helper
769
     */
770
    public function getHelper()
771
    {
772
        return $this->helper;
773
    }
774
775
    /**
776
     * @param mixed $basket
777
     */
778
    public function setBasket($basket)
779
    {
780
        $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...
781
        $this->prepareBasketForConnect();
782
    }
783
784
    /**
785
     * @return mixed
786
     */
787
    public function getBasket()
788
    {
789
        return $this->basket;
790
    }
791
792
    /**
793
     * @param array $connectContent
794
     */
795
    public function setConnectContent($connectContent)
796
    {
797
        $this->connectContent = $connectContent;
798
    }
799
800
    /**
801
     * @return array
802
     */
803
    public function getConnectContent()
804
    {
805
        return $this->connectContent;
806
    }
807
808
    /**
809
     * @param array $connectProducts
810
     */
811
    public function setConnectProducts($connectProducts)
812
    {
813
        $this->connectProducts = $connectProducts;
814
    }
815
816
    /**
817
     * @return array
818
     */
819
    public function getConnectProducts()
820
    {
821
        return $this->connectProducts;
822
    }
823
824
    /**
825
     * @param array $connectShops
826
     */
827
    public function setConnectShops($connectShops)
828
    {
829
        $this->connectShops = $connectShops;
830
    }
831
832
    /**
833
     * @return array
834
     */
835
    public function getConnectShops()
836
    {
837
        return $this->connectShops;
838
    }
839
840
    /**
841
     * @return array
842
     */
843
    public function getConnectGrossShippingCosts()
844
    {
845
        $result = [];
846
        if (!$this->checkResult instanceof CheckResult) {
847
            return $result;
848
        }
849
850
        foreach ($this->checkResult->shippingCosts as $shipping) {
851
            if ($this->hasTax()) {
852
                $result[$shipping->shopId] = $shipping->grossShippingCosts;
853
            } else {
854
                $result[$shipping->shopId] = $shipping->shippingCosts;
855
            }
856
        }
857
858
        return $result;
859
    }
860
861
    /**
862
     * @param mixed $originalShippingCosts
863
     */
864
    public function setOriginalShippingCosts($originalShippingCosts)
865
    {
866
        $this->originalShippingCosts = $originalShippingCosts;
867
    }
868
869
    /**
870
     * @return mixed
871
     */
872
    public function getOriginalShippingCosts()
873
    {
874
        return $this->originalShippingCosts;
875
    }
876
877
    /**
878
     * @param \Enlight_Components_Db_Adapter_Pdo_Mysql $database
879
     */
880
    public function setDatabase($database)
881
    {
882
        $this->database = $database;
883
    }
884
885
    /**
886
     * @return \Enlight_Components_Db_Adapter_Pdo_Mysql
887
     */
888
    public function getDatabase()
889
    {
890
        return $this->database;
891
    }
892
893
    /**
894
     * Returns "Gross price displayed in frontend" value
895
     * @return bool
896
     */
897
    protected function hasTax()
898
    {
899
        $customerGroup = Shopware()->Session()->sUserGroup;
900
        if (!$customerGroup) {
901
            $customerGroup = 'EK';
902
        }
903
904
        $repository = Shopware()->Models()->getRepository('Shopware\Models\Customer\Group');
905
        $groupModel = $repository->findOneBy(['key' => $customerGroup]);
906
907
        return $groupModel->getTax();
908
    }
909
910
    /**
911
     * @return \Shopware\Connect\Struct\CheckResult
912
     */
913
    public function getCheckResult()
914
    {
915
        return $this->checkResult ?: new CheckResult();
916
    }
917
918
    /**
919
     * @param \Shopware\Connect\Struct\CheckResult $checkResult
920
     */
921
    public function setCheckResult(CheckResult $checkResult)
922
    {
923
        $this->checkResult = $checkResult;
924
    }
925
926
    private function getConfig()
927
    {
928
        return ConfigFactory::getConfigInstance();
929
    }
930
}
931