Completed
Push — master ( d4c4e0...310bdb )
by Sebastian
13s
created

BasketHelper::getConnectContent()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
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->determineProductTitle($message);
645
646
                if ($message->values['availability'] == 0) {
647
                    $message->message = $snippets->get(
648
                        'connect_product_out_of_stock_message_detailed',
649
                        'Das Produkt "%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_detailed',
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 determineProductTitle(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 $product) {
682
                if ($product->sourceId == $message->values['product'] && $product->availability == 0) {
683
                    $message->values['ptitle'] = $product->title;
684
                    return;
685
                }
686
            }
687
        }
688
    }
689
690
    /**
691
     * Modifies a given OrderVariables ArrayObject
692
     *
693
     * @param $variables \ArrayObject
694
     * @return \ArrayObject
695
     */
696
    public function getOrderVariablesForSession($variables)
697
    {
698
        // Get a copy of the basket array in order to not mess up the state of the basket array
699
        $basket = $this->basket;
700
        $newVariables = $this->getDefaultTemplateVariables();
701
702
        // We need the manipulated content as the order is created from the session
703
        $basket['content'] = $basket['contentOrg'];
704
        unset($basket['contentOrg']);
705
706
707
        // Replace the original session array with the new one
708
        $variables->exchangeArray(array_merge(
709
            $variables->getArrayCopy(),
710
            $newVariables,
711
            ['sBasket' => $basket]
712
        ));
713
714
        return $variables;
715
    }
716
717
    /**
718
     * Find all percentaged vouchers for a given individual code
719
     *
720
     * @param $voucherCode
721
     * @return mixed
722
     */
723 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...
724
    {
725
        $builder = Shopware()->Models()->createQueryBuilder();
726
727
        $builder->select('voucher')
728
            ->from('Shopware\Models\Voucher\Voucher', 'voucher')
729
            ->innerJoin('voucher.codes', 'codes', 'WITH', 'codes.code LIKE :voucherCode')
730
            ->where('voucher.percental = true')
731
            ->setParameter('voucherCode', $voucherCode);
732
733
        return $builder->getQuery()->getResult();
734
    }
735
736
    /**
737
     * Find all vouchers matching the code
738
     *
739
     * @param $voucherCode
740
     * @return mixed
741
     */
742 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...
743
    {
744
        $builder = Shopware()->Models()->createQueryBuilder();
745
746
        $builder->select('voucher')
747
            ->from('Shopware\Models\Voucher\Voucher', 'voucher')
748
            ->where('voucher.voucherCode LIKE :voucherCode')
749
            ->andWhere('voucher.percental = true')
750
            ->setParameter('voucherCode', $voucherCode);
751
752
        return $builder->getQuery()->getResult();
753
    }
754
755
    /**
756
     * @return \Shopware\Connect\SDk
757
     */
758
    public function getSdk()
759
    {
760
        return $this->sdk;
761
    }
762
763
    /**
764
     * @return Helper
765
     */
766
    public function getHelper()
767
    {
768
        return $this->helper;
769
    }
770
771
    /**
772
     * @param mixed $basket
773
     */
774
    public function setBasket($basket)
775
    {
776
        $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...
777
        $this->prepareBasketForConnect();
778
    }
779
780
    /**
781
     * @return mixed
782
     */
783
    public function getBasket()
784
    {
785
        return $this->basket;
786
    }
787
788
    /**
789
     * @param array $connectContent
790
     */
791
    public function setConnectContent($connectContent)
792
    {
793
        $this->connectContent = $connectContent;
794
    }
795
796
    /**
797
     * @return array
798
     */
799
    public function getConnectContent()
800
    {
801
        return $this->connectContent;
802
    }
803
804
    /**
805
     * @param array $connectProducts
806
     */
807
    public function setConnectProducts($connectProducts)
808
    {
809
        $this->connectProducts = $connectProducts;
810
    }
811
812
    /**
813
     * @return array
814
     */
815
    public function getConnectProducts()
816
    {
817
        return $this->connectProducts;
818
    }
819
820
    /**
821
     * @param array $connectShops
822
     */
823
    public function setConnectShops($connectShops)
824
    {
825
        $this->connectShops = $connectShops;
826
    }
827
828
    /**
829
     * @return array
830
     */
831
    public function getConnectShops()
832
    {
833
        return $this->connectShops;
834
    }
835
836
    /**
837
     * @return array
838
     */
839
    public function getConnectGrossShippingCosts()
840
    {
841
        $result = [];
842
        if (!$this->checkResult instanceof CheckResult) {
843
            return $result;
844
        }
845
846
        foreach ($this->checkResult->shippingCosts as $shipping) {
847
            if ($this->hasTax()) {
848
                $result[$shipping->shopId] = $shipping->grossShippingCosts;
849
            } else {
850
                $result[$shipping->shopId] = $shipping->shippingCosts;
851
            }
852
        }
853
854
        return $result;
855
    }
856
857
    /**
858
     * @param mixed $originalShippingCosts
859
     */
860
    public function setOriginalShippingCosts($originalShippingCosts)
861
    {
862
        $this->originalShippingCosts = $originalShippingCosts;
863
    }
864
865
    /**
866
     * @return mixed
867
     */
868
    public function getOriginalShippingCosts()
869
    {
870
        return $this->originalShippingCosts;
871
    }
872
873
    /**
874
     * @param \Enlight_Components_Db_Adapter_Pdo_Mysql $database
875
     */
876
    public function setDatabase($database)
877
    {
878
        $this->database = $database;
879
    }
880
881
    /**
882
     * @return \Enlight_Components_Db_Adapter_Pdo_Mysql
883
     */
884
    public function getDatabase()
885
    {
886
        return $this->database;
887
    }
888
889
    /**
890
     * Returns "Gross price displayed in frontend" value
891
     * @return bool
892
     */
893
    protected function hasTax()
894
    {
895
        $customerGroup = Shopware()->Session()->sUserGroup;
896
        if (!$customerGroup) {
897
            $customerGroup = 'EK';
898
        }
899
900
        $repository = Shopware()->Models()->getRepository('Shopware\Models\Customer\Group');
901
        $groupModel = $repository->findOneBy(['key' => $customerGroup]);
902
903
        return $groupModel->getTax();
904
    }
905
906
    /**
907
     * @return \Shopware\Connect\Struct\CheckResult
908
     */
909
    public function getCheckResult()
910
    {
911
        return $this->checkResult ?: new CheckResult();
912
    }
913
914
    /**
915
     * @param \Shopware\Connect\Struct\CheckResult $checkResult
916
     */
917
    public function setCheckResult(CheckResult $checkResult)
918
    {
919
        $this->checkResult = $checkResult;
920
    }
921
}
922