Completed
Pull Request — master (#448)
by Stefan
05:13
created

BasketHelper::fixBasket()   B

Complexity

Conditions 4
Paths 2

Size

Total Lines 33
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 19
nc 2
nop 0
dl 0
loc 33
rs 8.5806
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
    /**
26
     * The basket array decorated by this class
27
     * @var array
28
     */
29
    protected $basket;
30
31
    /**
32
     * Array of connect product structs
33
     * @var array
34
     */
35
    protected $connectProducts = [];
36
37
    /**
38
     * connect content as formated by shopware
39
     *
40
     * @var array
41
     */
42
    protected $connectContent = [];
43
44
    /**
45
     * Array of connect shops affected by this basket
46
     *
47
     * @var array
48
     */
49
    protected $connectShops = [];
50
51
    /**
52
     * @var \Shopware\Connect\Struct\CheckResult
53
     */
54
    protected $checkResult;
55
56
    /**
57
     * The original shopware shipping costs
58
     *
59
     * @var float
60
     */
61
    protected $originalShippingCosts = 0;
62
63
    /**
64
     * Should there be a connect hint in the template
65
     *
66
     * @var bool
67
     */
68
    protected $showCheckoutShopInfo;
69
70
    /**
71
     * @var \Shopware\Connect\SDK
72
     */
73
    protected $sdk;
74
75
    /**
76
     * @var \Enlight_Components_Db_Adapter_Pdo_Mysql
77
     */
78
    protected $database;
79
80
    /**
81
     * @var Helper
82
     */
83
    protected $helper;
84
85
    /**
86
     * @var \Shopware\Connect\Gateway\PDO
87
     */
88
    protected $connectGateway;
89
90
    /**
91
     * Indicates if the basket has only connect products or not
92
     *
93
     * @var bool
94
     */
95
    protected $onlyConnectProducts = false;
96
97
    /**
98
     * @param \Enlight_Components_Db_Adapter_Pdo_Mysql $database
99
     * @param \Shopware\Connect\SDK $sdk
100
     * @param Helper $helper
101
     * @param $showCheckoutShopInfo
102
     */
103
    public function __construct(
104
        \Enlight_Components_Db_Adapter_Pdo_Mysql $database,
105
        SDK $sdk,
106
        Helper $helper,
107
        PDO $connectGateway,
108
        $showCheckoutShopInfo)
109
    {
110
        $this->database = $database;
111
        $this->sdk = $sdk;
112
        $this->helper = $helper;
113
        $this->connectGateway = $connectGateway;
114
        $this->showCheckoutShopInfo = $showCheckoutShopInfo;
115
    }
116
117
    /**
118
     * Prepare the basket for connect
119
     *
120
     * @return void
121
     */
122
    public function prepareBasketForConnect()
123
    {
124
        $this->buildProductsArray();
125
        $this->buildShopsArray();
126
    }
127
128
    /**
129
     * Build array of connect products. This will remove connect products from the 'content' array
130
     */
131
    protected function buildProductsArray()
132
    {
133
        $this->connectProducts = [];
134
        $this->connectContent = [];
135
136
        $this->basket['contentOrg'] = $this->basket['content'];
137
138
        foreach ($this->basket['content'] as $key => &$row) {
139
            if (!empty($row['mode'])) {
140
                continue;
141
            }
142
143
            $articleDetailId = $row['additional_details']['articleDetailsID'];
144
            if ($this->helper->isRemoteArticleDetailDBAL($articleDetailId) === false) {
145
                continue;
146
            }
147
148
            $shopProductId = $this->helper->getShopProductId($articleDetailId);
149
            $products = $this->getHelper()->getRemoteProducts([$shopProductId->sourceId], $shopProductId->shopId);
150
            if (empty($products)) {
151
                continue;
152
            }
153
            $product = reset($products);
154
            if ($product === null || $product->shopId === null) {
155
                continue;
156
            }
157
            $row['connectShopId'] = $product->shopId;
158
            $this->connectProducts[$product->shopId][$product->sourceId] = $product;
159
            $this->connectContent[$product->shopId][$product->sourceId] = $row;
160
161
            //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...
162
            unset($this->basket['content'][$key]);
163
            //}
164
        }
165
    }
166
167
    /**
168
     * Build array of connect remote shops
169
     */
170
    protected function buildShopsArray()
171
    {
172
        $this->connectShops = [];
173
174
        $this->basket['content'] = array_values($this->basket['content']);
175
        foreach ($this->connectContent as $shopId => $items) {
176
            $this->connectShops[$shopId] = $this->getSdk()->getShop($shopId);
177
        }
178
    }
179
180
    /**
181
     * Returns the quantity of a given product in the sw basket
182
     *
183
     * @param \Shopware\Connect\Struct\Product $product
184
     * @return mixed
185
     */
186
    public function getQuantityForProduct(Product $product)
187
    {
188
        if (isset($this->connectContent[$product->shopId]) &&
189
            isset($this->connectContent[$product->shopId][$product->sourceId])
190
        ) {
191
            return (int) $this->connectContent[$product->shopId][$product->sourceId]['quantity'];
192
        } elseif (isset($this->basket['content'][$product->sourceId])) {
193
            return (int) $this->basket['content'][$product->sourceId]['quantity'];
194
        }
195
196
        return 1;
197
    }
198
199
    /**
200
     * This method will check, if any *real* products from the local shop are in the basket. If this is not the
201
     * case, this method will:
202
     *
203
     * - set the first connect shop as content of the default basket ($basket['content'])
204
     * - remove any surcharges, vouchers and  discount from the original basket(!)
205
     *
206
     * @return bool|mixed
207
     */
208
    public function fixBasket()
209
    {
210
        // Filter out basket items which cannot be purchased on their own
211
        $content = array_filter($this->basket['content'], function ($item) {
212
            switch ((int) $item['modus']) {
213
                    case 0: // Default products
214
                    case 1: // Premium products
215
                        return true;
216
                    default:
217
                        return false;
218
                }
219
        });
220
221
        // If only connect products are in the basket, do the basket fix
222
        if (empty($content)) {
223
            $this->onlyConnectProducts = true;
224
225
            $this->removeNonProductsFromBasket();
226
            $this->basket = $this->removeDefaultShipping($this->basket);
227
228
            $connectContent = $this->getConnectContent();
229
230
            // Make the first connect shop the default basket-content
231
            reset($connectContent);
232
            $shopId = current(array_keys($connectContent));
233
            $this->basket['content'] = $connectContent[$shopId];
234
            unset($this->connectContent[$shopId]);
235
236
            return $shopId;
237
        }
238
239
        return false;
240
    }
241
242
    /**
243
     * Remove shipping costs from given basket
244
     *
245
     * @param array $basket
246
     * @return array
247
     */
248
    private function removeDefaultShipping(array $basket)
249
    {
250
        $basket['AmountNumeric'] -= $basket['sShippingcosts'];
251
        $basket['AmountNetNumeric'] -= $basket['sShippingcostsNet'];
252
253
        $basketHasTax = $this->hasTax();
254
        if (!empty($this->basket['sAmountWithTax'])) {
255
            if ($basketHasTax) {
256
                $this->basket['sAmountWithTax'] -= $basket['sShippingcosts'];
257
            } else {
258
                $this->basket['sAmountWithTax'] -= $basket['sShippingcostsNet'];
259
            }
260
        }
261
262
        if ($basketHasTax) {
263
            $basket['sAmount'] -= $basket['sShippingcosts'];
264
        } else {
265
            $basket['sAmount'] -= $basket['sShippingcostsNet'];
266
        }
267
268
        $basket['sShippingcosts'] = 0;
269
        $basket['sShippingcostsNet'] = 0;
270
        $basket['sShippingcostsWithTax'] = 0;
271
272
        return $basket;
273
    }
274
275
    /**
276
     * Removes non-connect products from the database and fixes the basket variables
277
     */
278
    protected function removeNonProductsFromBasket()
279
    {
280
        $removeItems = [
281
            'ids' => [],
282
            'price' => 0,
283
            'netprice' => 0,
284
            'sessionId' => null
285
        ];
286
287
        // Build array of ids and amount to fix the basket later
288
        foreach ($this->basket['content'] as  $key => $product) {
289
            $removeItems['ids'][] = $product['id'];
290
            $removeItems['price'] += $product['price'] * $product['quantity'];
291
            $removeItems['amountWithTax'] += $product['amountWithTax'] * $product['quantity'];
292
            $removeItems['netprice'] += $product['netprice'] * $product['quantity'];
293
            $removeItems['tax'] += str_replace(',', '.', $product['tax']) * $product['quantity'];
294
            $removeItems['sessionId'] = $product['sessionID'];
295
296
            // Remove surcharge, cannot be deleted with SQL
297
            if ($product['modus'] == 4) {
298
                unset($this->basket['content'][$key]);
299
            }
300
        }
301
302
        if (empty($removeItems['ids'])) {
303
            return;
304
        }
305
306
        // Fix basket prices
307
        $this->basket['AmountNumeric'] -= $removeItems['price'];
308
        $this->basket['AmountNetNumeric'] -= $removeItems['netprice'];
309
        $this->basket['sAmount'] -= $removeItems['price'];
310
        $this->basket['Amount'] = str_replace(',', '.', $this->basket['Amount']) - $removeItems['price'];
311
312
        $this->basket['sAmountTax'] -= $removeItems['tax'];
313
        if (!empty($this->basket['sAmountWithTax'])) {
314
            if ($this->hasTax()) {
315
                $this->basket['sAmountWithTax'] -= $removeItems['price'];
316
            } else {
317
                $this->basket['sAmountWithTax'] -= $removeItems['amountWithTax'];
318
                $this->basket['AmountWithTaxNumeric'] -= $removeItems['amountWithTax'];
319
                $this->basket['AmountWithTax'] = $this->basket['AmountWithTaxNumeric'];
320
                $this->basket['amountnet'] = $this->basket['amount'];
321
            }
322
        }
323
324
        // Remove items from basket
325
        $this->getDatabase()->query(
326
            'DELETE FROM s_order_basket WHERE sessionID = ? and id IN (?)',
327
            [
328
                $removeItems['sessionId'],
329
                implode(',', $removeItems['ids'])
330
            ]
331
        );
332
333
        // Filter out basket items - surcharge
334
        $this->basket['contentOrg'] = array_filter($this->basket['contentOrg'], function ($item) {
335
            switch ((int) $item['modus']) {
336
                case 4: // Surcharge
337
                    return false;
338
                default:
339
                    return true;
340
            }
341
        });
342
    }
343
344
    /**
345
     * @todo: This function is basically a copy of the same function in Controllers/Frontend/Checkout.
346
     * As that function cannot be called, I copied it for the time being - this should be refactored
347
     *
348
     * @param  $basket array returned from this->getBasket
349
     * @return array
350
     */
351
    public function getTaxRates($basket)
352
    {
353
        $result = [];
354
355
        // The original method also calculates the tax rates of the shipping costs - this
356
        // is done in a separate methode here
357
358
        if (empty($basket['content'])) {
359
            ksort($result, SORT_NUMERIC);
360
361
            return $result;
362
        }
363
364
        foreach ($basket['content'] as $item) {
365
            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...
366
            } elseif (!empty($item['taxPercent'])) {
367
                $item['tax_rate'] = $item['taxPercent'];
368
            } elseif ($item['modus'] == 2) {
369
                // Ticket 4842 - dynamic tax-rates
370
                $resultVoucherTaxMode = Shopware()->Db()->fetchOne(
371
                    'SELECT taxconfig FROM s_emarketing_vouchers WHERE ordercode=?
372
                ', [$item['ordernumber']]);
373
                // Old behaviour
374
                if (empty($resultVoucherTaxMode) || $resultVoucherTaxMode == 'default') {
375
                    $tax = Shopware()->Config()->get('sVOUCHERTAX');
376
                } elseif ($resultVoucherTaxMode == 'auto') {
377
                    // Automatically determinate tax
378
                    $tax = Shopware()->Modules()->Basket()->getMaxTax();
379
                } elseif ($resultVoucherTaxMode == 'none') {
380
                    // No tax
381
                    $tax = '0';
382
                } elseif (intval($resultVoucherTaxMode)) {
383
                    // Fix defined tax
384
                    $tax = Shopware()->Db()->fetchOne('
385
					SELECT tax FROM s_core_tax WHERE id = ?
386
					', [$resultVoucherTaxMode]);
387
                }
388
                $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...
389
            } else {
390
                // Ticket 4842 - dynamic tax-rates
391
                $taxAutoMode = Shopware()->Config()->get('sTAXAUTOMODE');
392
                if (!empty($taxAutoMode)) {
393
                    $tax = Shopware()->Modules()->Basket()->getMaxTax();
394
                } else {
395
                    $tax = Shopware()->Config()->get('sDISCOUNTTAX');
396
                }
397
                $item['tax_rate'] = $tax;
398
            }
399
400
            // Ignore 0 % tax
401
            if (empty($item['tax_rate']) || empty($item['tax'])) {
402
                continue;
403
            }
404
            $taxKey = number_format(floatval($item['tax_rate']), 2);
405
            $result[$taxKey] += str_replace(',', '.', $item['tax']);
406
        }
407
408
        ksort($result, SORT_NUMERIC);
409
410
        return $result;
411
    }
412
413
    /**
414
     * Returns an array of tax positions in the same way, as shopware does in the sTaxRates.
415
     * This will only take connect products returned by getConnectContent() into account,
416
     * so that connect positions moved into basket['content'] earlier are not calculated twice.
417
     *
418
     * @return array
419
     */
420
    public function getConnectTaxRates()
421
    {
422
        $taxes = [];
423
424
        foreach ($this->getConnectContent() as $shopId => $products) {
425
            foreach ($products as $product) {
426
                $vat = (string) number_format($product['tax_rate'], 2);
427
                if (!isset($taxes[$vat])) {
428
                    $taxes[$vat] = 0;
429
                }
430
431
                if ($this->hasTax()) {
432
                    $taxes[$vat] += $product['priceNumeric'] - $product['netprice'];
433
                } else {
434
                    $taxes[$vat] += $product['amountWithTax'] - ($product['netprice'] * $product['quantity']);
435
                }
436
            }
437
        }
438
439
        return $taxes;
440
    }
441
442
    /**
443
     * Will merge/add various arrays of "sTaxRates" like arrays into one array
444
     *
445
     * @param array $taxRates
446
     * @return array
447
     */
448
    public function getMergedTaxRates(array $taxRates)
449
    {
450
        $result = [];
451
452
        foreach ($taxRates as $taxRate) {
453
            foreach ($taxRate as $vat => $amount) {
454
                if (!isset($result[$vat])) {
455
                    $result[$vat] = 0;
456
                }
457
                $result[$vat] += $amount;
458
            }
459
        }
460
461
        return $result;
462
    }
463
464
    /**
465
     * Increase the basket's shipping costs and amount by the total value of connect shipping costs
466
     *
467
     * @param \Shopware\Connect\Struct\CheckResult $checkResult
468
     */
469
    public function recalculate(CheckResult $checkResult)
470
    {
471
        $this->checkResult = $checkResult;
472
        $this->basket['sAmount'] = number_format($this->basket['sAmount'], 2, '.', '');
473
474
        $shippingCostsNet = 0;
475
        $shippingCostsWithTax = 0;
476
477
        /** @var \Shopware\Connect\Struct\Shipping $shipping */
478
        foreach ($this->checkResult->shippingCosts as $shipping) {
479
            $shopConfiguration = $this->connectGateway->getShopConfiguration($shipping->shopId);
480
            if ($shopConfiguration->shippingCostType == 'remote') {
481
                $shippingCostsNet += $shipping->shippingCosts;
482
                $shippingCostsWithTax += $shipping->grossShippingCosts;
483
            }
484
        }
485
        $shippingCostsNet = number_format($shippingCostsNet, 2, '.', '');
486
        $shippingCostsWithTax = number_format($shippingCostsWithTax, 2, '.', '');
487
488
        $basketHasTax = $this->hasTax();
489
490
        // Set the shipping cost tax rate for shopware
491
492
        $this->setOriginalShippingCosts($this->basket['sShippingcosts']);
493
494
        // Update shipping costs
495
        if ($basketHasTax) {
496
            $this->basket['sShippingcosts'] += $shippingCostsWithTax;
497
        } else {
498
            $this->basket['sShippingcosts'] += $shippingCostsNet;
499
        }
500
        $this->basket['sShippingcostsNet'] += $shippingCostsNet;
501
        $this->basket['sShippingcostsWithTax'] += $shippingCostsWithTax;
502
503
        $this->basket['AmountNetNumeric'] += $shippingCostsNet;
504
505
        if (!empty($this->basket['sAmountWithTax'])) {
506
            if ($basketHasTax) {
507
                $this->basket['sAmountWithTax'] += $this->basket['sShippingcostsWithTax'];
508
            } else {
509
                $this->basket['sAmountWithTax'] += $shippingCostsWithTax;
510
            }
511
        }
512
513
        if ($basketHasTax) {
514
            $this->basket['sAmount'] += $shippingCostsWithTax;
515
        } else {
516
            $this->basket['sAmount'] += $shippingCostsNet;
517
        }
518
519
        $this->basket['sAmountTax'] += $this->basket['sShippingcostsWithTax'] - $shippingCostsNet;
520
521
        // Core workaround: Shopware tries to re-calculate the shipping tax rate from the net price
522
        // \Shopware_Models_Document_Order::processOrder
523
        // Therefore we need to round the net price
524
        $this->basket['sShippingcostsNet'] = round($this->basket['sShippingcostsNet'], 2);
525
526
527
        // Recalculate the tax rates
528
        $this->basket['sTaxRates'] = $this->getMergedTaxRates(
529
            [
530
                $this->getTaxRates($this->basket),
531
                $this->getConnectTaxRates(),
532
                $this->getShippingCostsTaxRates()
533
            ]
534
        );
535
536
        //@todo:stefan Check for better solution
537
        $this->basket['AmountWithTaxNumeric'] = $this->basket['sAmountWithTax'];
538
        $this->basket['AmountNumeric'] = $this->basket['sAmount'];
539
    }
540
541
    /**
542
     * Returns the tax rate of the shipping costs and also sets the the net shipping cost amount(!)
543
     */
544
    public function getShippingCostsTaxRates()
545
    {
546
        $taxAmount = $this->basket['sShippingcostsWithTax'] - $this->basket['sShippingcostsNet'];
547
548
        $taxRate = number_format($this->getMaxTaxRate(), 2, '.', '');
549
        $this->basket['sShippingcostsNet'] = $this->basket['sShippingcostsWithTax'] / (($taxRate/100)+1);
550
551
        return [
552
            (string) $taxRate => $taxAmount
553
        ];
554
    }
555
556
    /**
557
     * Get the highest tax rate from basket - currently only this is supported by SW
558
     *
559
     * @return int
560
     */
561
    public function getMaxTaxRate()
562
    {
563
        $taxRate = 0;
564
        foreach ($this->getConnectContent() as $shopId => $products) {
565
            foreach ($products as $product) {
566
                if ($product['tax_rate'] > $taxRate) {
567
                    $taxRate = $product['tax_rate'];
568
                }
569
            }
570
        }
571
572
        foreach ($this->basket['content'] as $product) {
573
            if ($product['tax_rate'] > $taxRate) {
574
                $taxRate = $product['tax_rate'];
575
            }
576
        }
577
578
        return $taxRate;
579
    }
580
581
    /**
582
     * Return array of variables which need to be available in the default template
583
     *
584
     * @return array
585
     */
586
    public function getDefaultTemplateVariables()
587
    {
588
        return [
589
            'sBasket' => $this->basket,
590
            'sShippingcosts' => $this->basket['sShippingcosts'],
591
            'sAmount' => $this->basket['sAmount'],
592
            'sAmountWithTax' => $this->basket['sAmountWithTax'],
593
            'sAmountNet' => $this->basket['AmountNetNumeric']
594
        ];
595
    }
596
597
    /**
598
     * Return array of connect specific template variables
599
     *
600
     * @param $connectMessages array Messages to show
601
     * @return array
602
     */
603
    public function getConnectTemplateVariables(array $connectMessages)
604
    {
605
        $snippets = Shopware()->Snippets()->getNamespace('frontend/checkout/error_messages');
606
        /** @var Message $message */
607
        foreach ($connectMessages as $message) {
608
            if ($message->message == 'Availability of product %product changed to %availability.') {
609
                if ($message->values['availability'] == 0) {
610
                    $message->message = $snippets->get(
611
                        'connect_product_out_of_stock_message',
612
                        'Produkte in Ihrer Bestellung sind aktuell nicht lieferbar, bitte entfernen Sie die Produkte um fortzufahren.'
613
                    );
614
                } else {
615
                    $message->message = $snippets->get(
616
                        'connect_product_lower_stock_message',
617
                        'Der Lagerbestand von Produkt "%product" hat sich auf %availability geändert'
618
                    );
619
                }
620
            }
621
        }
622
623
        return [
624
            'connectContent' => $this->getConnectContent(),
625
            'connectShops' => $this->getConnectShops(),
626
            'connectMessages' => $connectMessages,
627
            'connectShippingCosts' => $this->getConnectGrossShippingCosts(),
628
            'connectShippingCostsOrg' => $this->getOriginalShippingCosts(),
629
            'connectShopInfo' => $this->showCheckoutShopInfo,
630
            'addBaseShop' => $this->onlyConnectProducts ? 0 : 1,
631
        ];
632
    }
633
634
    /**
635
     * Modifies a given OrderVariables ArrayObject
636
     *
637
     * @param $variables \ArrayObject
638
     * @return \ArrayObject
639
     */
640
    public function getOrderVariablesForSession($variables)
641
    {
642
        // Get a copy of the basket array in order to not mess up the state of the basket array
643
        $basket = $this->basket;
644
        $newVariables = $this->getDefaultTemplateVariables();
645
646
        // We need the manipulated content as the order is created from the session
647
         $basket['content'] = $basket['contentOrg'];
648
        unset($basket['contentOrg']);
649
650
651
        // Replace the original session array with the new one
652
        $variables->exchangeArray(array_merge(
653
            $variables->getArrayCopy(), $newVariables, ['sBasket' => $basket]
654
        ));
655
656
        return $variables;
657
    }
658
659
    /**
660
     * Find all percentaged vouchers for a given individual code
661
     *
662
     * @param $voucherCode
663
     * @return mixed
664
     */
665 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...
666
    {
667
        $builder = Shopware()->Models()->createQueryBuilder();
668
669
        $builder->select('voucher')
670
            ->from('Shopware\Models\Voucher\Voucher', 'voucher')
671
            ->innerJoin('voucher.codes', 'codes', 'WITH', 'codes.code LIKE :voucherCode')
672
            ->where('voucher.percental = true')
673
            ->setParameter('voucherCode', $voucherCode);
674
675
        return $builder->getQuery()->getResult();
676
    }
677
678
    /**
679
     * Find all vouchers matching the code
680
     *
681
     * @param $voucherCode
682
     * @return mixed
683
     */
684 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...
685
    {
686
        $builder = Shopware()->Models()->createQueryBuilder();
687
688
        $builder->select('voucher')
689
            ->from('Shopware\Models\Voucher\Voucher', 'voucher')
690
            ->where('voucher.voucherCode LIKE :voucherCode')
691
            ->andWhere('voucher.percental = true')
692
            ->setParameter('voucherCode', $voucherCode);
693
694
        return $builder->getQuery()->getResult();
695
    }
696
697
    /**
698
     * @return \Shopware\Connect\SDk
699
     */
700
    public function getSdk()
701
    {
702
        return $this->sdk;
703
    }
704
705
    /**
706
     * @return Helper
707
     */
708
    public function getHelper()
709
    {
710
        return $this->helper;
711
    }
712
713
    /**
714
     * @param mixed $basket
715
     */
716
    public function setBasket($basket)
717
    {
718
        $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...
719
        $this->prepareBasketForConnect();
720
    }
721
722
    /**
723
     * @return mixed
724
     */
725
    public function getBasket()
726
    {
727
        return $this->basket;
728
    }
729
730
    /**
731
     * @param array $connectContent
732
     */
733
    public function setConnectContent($connectContent)
734
    {
735
        $this->connectContent = $connectContent;
736
    }
737
738
    /**
739
     * @return array
740
     */
741
    public function getConnectContent()
742
    {
743
        return $this->connectContent;
744
    }
745
746
    /**
747
     * @param array $connectProducts
748
     */
749
    public function setConnectProducts($connectProducts)
750
    {
751
        $this->connectProducts = $connectProducts;
752
    }
753
754
    /**
755
     * @return array
756
     */
757
    public function getConnectProducts()
758
    {
759
        return $this->connectProducts;
760
    }
761
762
    /**
763
     * @param array $connectShops
764
     */
765
    public function setConnectShops($connectShops)
766
    {
767
        $this->connectShops = $connectShops;
768
    }
769
770
    /**
771
     * @return array
772
     */
773
    public function getConnectShops()
774
    {
775
        return $this->connectShops;
776
    }
777
778
    /**
779
     * @return array
780
     */
781
    public function getConnectGrossShippingCosts()
782
    {
783
        $result = [];
784
        if (!$this->checkResult instanceof CheckResult) {
785
            return $result;
786
        }
787
788
        foreach ($this->checkResult->shippingCosts as $shipping) {
789
            if ($this->hasTax()) {
790
                $result[$shipping->shopId] = $shipping->grossShippingCosts;
791
            } else {
792
                $result[$shipping->shopId] = $shipping->shippingCosts;
793
            }
794
        }
795
796
        return $result;
797
    }
798
799
    /**
800
     * @param mixed $originalShippingCosts
801
     */
802
    public function setOriginalShippingCosts($originalShippingCosts)
803
    {
804
        $this->originalShippingCosts = $originalShippingCosts;
805
    }
806
807
    /**
808
     * @return mixed
809
     */
810
    public function getOriginalShippingCosts()
811
    {
812
        return $this->originalShippingCosts;
813
    }
814
815
    /**
816
     * @param \Enlight_Components_Db_Adapter_Pdo_Mysql $database
817
     */
818
    public function setDatabase($database)
819
    {
820
        $this->database = $database;
821
    }
822
823
    /**
824
     * @return \Enlight_Components_Db_Adapter_Pdo_Mysql
825
     */
826
    public function getDatabase()
827
    {
828
        return $this->database;
829
    }
830
831
    /**
832
     * Returns "Gross price displayed in frontend" value
833
     * @return bool
834
     */
835
    protected function hasTax()
836
    {
837
        $customerGroup = Shopware()->Session()->sUserGroup;
838
        if (!$customerGroup) {
839
            $customerGroup = 'EK';
840
        }
841
842
        $repository = Shopware()->Models()->getRepository('Shopware\Models\Customer\Group');
843
        $groupModel = $repository->findOneBy(['key' => $customerGroup]);
844
845
        return $groupModel->getTax();
846
    }
847
848
    /**
849
     * @return \Shopware\Connect\Struct\CheckResult
850
     */
851
    public function getCheckResult()
852
    {
853
        return $this->checkResult ?: new CheckResult();
854
    }
855
856
    /**
857
     * @param \Shopware\Connect\Struct\CheckResult $checkResult
858
     */
859
    public function setCheckResult(CheckResult $checkResult)
860
    {
861
        $this->checkResult = $checkResult;
862
    }
863
}
864