Completed
Push — master ( 529bfd...1b9763 )
by Stefan
02:58
created

saveOrderAttribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
eloc 10
nc 2
nop 3
1
<?php
2
3
use Shopware\Components\CSRFWhitelistAware;
4
5
/**
6
 * Klarna payment controller
7
 */
8
class Shopware_Controllers_Frontend_PaymentKlarna extends Shopware_Controllers_Frontend_Payment implements CSRFWhitelistAware
9
{
10
    /**
11
     * @var Shopware_Plugins_Frontend_SwagPaymentKlarna_Bootstrap
12
     */
13
    private $plugin;
14
15
    /**
16
     * @var Enlight_Config
17
     */
18
    private $config;
19
20
    private $basket;
21
22
    private $admin;
23
24
    private $session;
25
26
    /**
27
     * Init method that get called automatically
28
     *
29
     * Set class properties
30
     */
31
    public function init()
32
    {
33
        $this->admin = Shopware()->Modules()->Admin();
34
        $this->session = Shopware()->Session();
35
        $this->plugin = Shopware()->Container()->get('plugins')->Frontend()->SwagPaymentKlarna();
36
        $this->config = $this->plugin->Config();
37
    }
38
39
40
    /**
41
     * {@inheritdoc}
42
     */
43
    public function preDispatch()
44
    {
45
46
        if (in_array($this->Request()->getActionName(), ['push', 'saveFormData'])) {
47
            $this->Front()->Plugins()->ViewRenderer()->setNoRender();
48
        }
49
    }
50
    
51
    /**
52
     * whitelists indexAction for SW 5.2 compatibility
53
     */
54
    public function getWhitelistedCSRFActions()
55
    {
56
        return [
57
            'index',
58
            'express',
59
            'push',
60
            'login',
61
            'return',
62
            'showIframe',
63
            'calculateShippingCosts',
64
            'savePayment',
65
            'addVoucher',
66
            'deleteArticle',
67
            'saveFormData',
68
            'setPayment',
69
            'otherPayment',
70
        ];
71
    }
72
73
    /**
74
     * {@inheritdoc}
75
     */
76 View Code Duplication
    public function get($name)
0 ignored issues
show
Documentation introduced by
The return type could not be reliably inferred; please add a @return annotation.

Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a @return annotation as described here.

Loading history...
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...
77
    {
78
        if (version_compare(Shopware::VERSION, '4.2.0', '<') && Shopware::VERSION != '___VERSION___') {
79
            if ($name == 'pluginlogger') {
80
                $name = 'log';
81
            }
82
            $name = ucfirst($name);
83
            return Shopware()->Bootstrap()->getResource($name);
84
        }
85
        return parent::get($name);
86
    }
87
    
88
    /**
89
     * Index action method.
90
     *
91
     * Forwards to correct the action.
92
     */
93
    public function indexAction()
94
    {
95
        $this->redirect(['controller' => 'payment_klarna', 'action' => 'showIframe']);
96
    }
97
98
    /**
99
     * Express payment action method.
100
     */
101
    public function expressAction()
102
    {
103
        if (!empty($this->session->PaypalResponse)) {
104
            $this->plugin->klarnaLog("Paypal Payment in Progress detected Redirecting To Index Page", 3);
105
            $this->redirect(
106
                [
107
                    'controller' => 'index',
108
                    'action' => 'index'
109
                ]
110
            );
111
            return;
112
        }
113
        
114
        if ($this->Request()->getPost('sCountry')) {
115
            $this->session['sCountry'] = (int)$this->Request()->getPost('sCountry');
116
            $this->session["sState"] = 0;
117
            $this->session["sArea"] = Shopware()->Db()->fetchOne("
118
                SELECT areaID FROM s_core_countries WHERE id = ?
119
            ", [$this->session['sCountry']]);
120
            unset($this->session->KlarnaOrder);
121
            $this->session['sChangedCountry'] = (int)$this->Request()->getPost('sCountry');
122
        }
123
        $this->forward('index');
124
    }
125
126
127
    /**
128
     * Express Iframe Test
129
     */
130
    public function showIframeAction()
131
    {
132
        $this->basket = $this->get('modules')->Basket()->sGetBasket();
133
         $preFill = $this->config['preFillCheckout'];
134
        if ($this->isUserLoggedIn()) {
135
            $user = Shopware()->Modules()->Admin()->sGetUserData();
136
        }
137
138
        $paymentIdDebug = $this->plugin->getPayment()->getId();
139
140
        // set payment to klarna checkout
141
        $this->session['sPaymentID'] = $this->plugin->getPayment()->getId();
142
143
        $postedCountry = null;
144
        // Register Custom Template
145
        $this->View()->loadTemplate("frontend/checkout/confirm.tpl");
146
        // update dispatch or delivery country in case form was submitted
147
        if ($this->Request()->isPost()) {
148
            // set klarnaPrefill, in case User ovverides Setting with checkbox
149
            if ($this->Request()->getParam('klarnaPreFill') == "on") {
150
                $this->session['klarnaUserPreFill'] = true;
151
            }
152
153
            $this->setDispatch($this->Request()->getPost('sDispatch'));
154
            $postedCountry = $this->Request()->getPost('sCountry');
155
            if (!empty($postedCountry)) {
156
                $shopCountryId = $this->session['sCountry'];
157
                $validKlarnaCountry = $this->plugin->checkValidKlarnaCountry($postedCountry);
158
                if (!$validKlarnaCountry) {
159
                    $this->redirect(['controller' => 'payment_klarna', 'action' => 'otherPayment']);
160
                    return;
161
                }
162
                $shopCountryId = (string)$shopCountryId;
163
                if ($shopCountryId != $postedCountry) {
164
                    $this->session['sCountry'] = $postedCountry;
165
                    // unset klarnaOrder so it will be created with new countryID
166
                    unset($this->session['KlarnaOrder']);
167
                }
168
            }
169
            //$this->redirect(array('controller' => 'payment_klarna', 'action' => 'showIframe'));
0 ignored issues
show
Unused Code Comprehensibility introduced by
72% 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...
170
        } else {
171
            $this->setDispatch($this->session->sDispatch, $paymentIdDebug);
172
        }
173
        // set shipping costs (Overwrites $session->sCountry!)
174
        $debugShipping = $this->getShippingCosts();
175
        if ($postedCountry) {
176
            $this->session['sCountry'] = $postedCountry;
177
        } else {
178
            // set Default Country
179
            $bootstrap = $this->get('plugins')->get('Frontend')->get('SwagPaymentKlarna');
180
            $this->session['sCountry'] = $bootstrap->getCountryByShop(Shopware()->Shop());
181
        }
182
183
        $this->basket['sShippingcosts'] = $debugShipping['brutto'];
184
        $this->basket['sShippingcostsWithTax'] = $debugShipping['brutto'];
185
        $this->basket['sShippingcostsNet'] = $debugShipping['netto'];
186
        $this->basket['sShippingcostsTax'] = $debugShipping['tax'];
187
188
        // set missing basket vars for use in view
189
        $this->basket['AmountWithTaxNumeric'] = floatval(
190
            str_replace(',', '.', $this->basket['Amount'])
191
        ) + floatval(
192
            str_replace(',', '.', $debugShipping['brutto'])
193
        );
194
        $this->basket['AmountNetNumeric'] = floatval(str_replace(',', '.', $this->basket['AmountNet']));
195
196
        $klarnaConnector = $this->plugin->getConnector();
197
        $shop = $this->plugin->Application()->Shop();
198
199
        $create = [];
200
        $create['cart']['items'] = $this->plugin->getCheckoutCart($this->basket);
201
        $create['merchant'] = $this->plugin->getCheckoutMerchant();
202
203
        $create['purchase_country'] = $this->plugin->getCountryIsoById($this->session['sCountry']);
204
        $create['purchase_currency'] = $shop->getCurrency()->toString();
205
        $create['locale'] = $this->plugin->getLocale(false, $create['purchase_country']);
206
        $create['options'] = $this->plugin->getCheckoutOptions();
207
208
        if ($this->config->get('KlarnaExternalPayments')) {
209
            list($create['external_payment_methods'], $create['external_checkouts']) = $this->plugin
210
                ->getExternalPaymentMethods($this->basket);
211
        }
212
213
        if ($this->config->get('disableAutofocus')) {
214
            $create['gui']['options'] = ['disable_autofocus'];
215
        }
216
217
        // set Prefill Information
218
219
        if (($preFill == true) || ($this->session['klarnaUserPreFill'] == true)) {
220
            $this->session['klarnaPreFill'] = true;
221
            if (empty($session['sCountry'])) {
0 ignored issues
show
Bug introduced by
The variable $session seems to never exist, and therefore empty should always return true. Did you maybe rename this variable?

This check looks for calls to isset(...) or empty() on variables that are yet undefined. These calls will always produce the same result and can be removed.

This is most likely caused by the renaming of a variable or the removal of a function/method parameter.

Loading history...
222
                $bootstrap = $this->get('plugins')->get('Frontend')->get('SwagPaymentKlarna');
223
                $countryId = $bootstrap->getCountryByShop($shop);
224
            } else {
225
                $countryId = $session['sCountry'];
226
            }
227
            if ($user['additional']['countryShipping']['id'] == $countryId
228
                && $user['billingaddress']['zipcode'] != '00000'
229
            ) {
230
                $create['customer'] = $this->plugin->getCheckoutCustomer($user);
0 ignored issues
show
Bug introduced by
The variable $user 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...
231
                if ($user['additional']['countryShipping']['id'] == $user['additional']['country']['id']) {
232
                    $create['shipping_address'] = $this->plugin->getCheckoutAddress($user, 'billing');
233
                } else {
234
                    $create['shipping_address'] = $this->plugin->getCheckoutAddress($user, 'shipping');
235
                }
236
            }
237
        } else {
238
            $this->session['klarnaPreFill'] = false;
239
        }
240
241
        // In case Customer fills Iframe and then logs in do not update existing klarnaOrder
242
        if (!empty($this->session['KlarnaOrder']) && !$this->isUserLoggedIn()) {
243
            $klarnaOrder = new Klarna_Checkout_Order($klarnaConnector, $this->session['KlarnaOrder']);
0 ignored issues
show
Documentation introduced by
$klarnaConnector is of type object<Klarna_Checkout_Connector>, but the function expects a object<Klarna_Checkout_ConnectorInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
244
            $update = [];
245
            $update['cart']['items'] = $this->plugin->getCheckoutCart($this->basket);
246
            $update['purchase_country'] = $this->plugin->getCountryIsoById($this->session['sCountry']);
247
248
            $klarnaOrder->fetch();
249
            // update basket and delivery country in case it changed
250
            $klarnaOrder->update($update);
251
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
252
        } else {
253
            $klarnaOrder = new Klarna_Checkout_Order($klarnaConnector);
0 ignored issues
show
Documentation introduced by
$klarnaConnector is of type object<Klarna_Checkout_Connector>, but the function expects a object<Klarna_Checkout_ConnectorInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
254
            $klarnaOrder->create($create);
255
        }
256
257
258
        try {
259
            $klarnaOrder->fetch();
260
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
261
        } catch (Exception $e) {
262
            Shopware()->Plugins()->Controller()->ViewRenderer()->setNoRender();
263
            echo "Entschuldigung, Ein Verbindungsfehler ist aufgetreten, bitte aktualisieren Sie die Seite";
264
            $this->plugin->klarnaLog(
265
                "Verbindungsfehler in onPreDispatchCheckout\nCode:" . $e->getCode() . "Nachricht:\n" . $e->getMessage(),
266
                1
267
            );
268
        }
269
270
        $this->session->KlarnaOrder = $klarnaOrder->getLocation();
271
272
        // Delete old perhaps cancelled Klarna Order
273
274
        if ($klarnaOrder['status'] !== "checkout_incomplete") {
275
            unset($this->session->KlarnaOrder);
276
        }
277
278
        $userAdditionalArray = [];
279
        $userAdditionalArray['additional']['charge_vat'] = 1;
280
281
        $userPayment = [];
282
        $userPayment['id'] = $this->plugin->getPayment()->getId();
283
284
        // persist basket changes
285
        Shopware()->Session()->sOrderVariables['sBasket'] = $this->basket;
286
287
        // Klarna Iframe Information
288
        $this->View()->assign('KlarnaOrder', $klarnaOrder->marshal());
289
290
        // Klarna Prefill checkBox
291
        if ($this->isUserLoggedIn()) {
292
               $this->View()->assign('KlarnaPreFillSelect', !$this->session['klarnaPreFill']);
293
        }
294
295
        // Iframe Backend Config
296
        $this->plugin->getViewConfig($this->View(), $this->config);
297
        $this->View()->sBasket = $this->basket;
298
        $this->View()->sDispatches = $this->getDispatches($paymentIdDebug);
299
        if ($postedCountry) {
300
            $this->session['sCountry'] = $postedCountry;
301
        }
302
        $this->View()->sDispatch = $this->getSelectedDispatch();
303
304
        // Neccessary if user is not logged in
305
        $this->View()->sPayment = $userPayment;
306
307
        $this->basket['sShippingcosts'] = $debugShipping['brutto'];
308
        $this->basket['sShippingcostsWithTax'] = $debugShipping['brutto'];
309
        $this->basket['sShippingcostsNet'] = $debugShipping['netto'];
310
        $this->basket['sShippingcostsTax'] = $debugShipping['tax'];
311
312
        $this->basket['sAmount'] = floatval($this->basket['Amount']) + floatval($this->basket['sShippingcosts']);
313
        $this->basket['sAmountNet'] = floatval($this->basket['AmountNetNumeric']) + floatval($debugShipping['netto']);
314
315
        $this->basket['sAmountTax'] = 1.9;
316
        $this->View()->sShippingcosts = $debugShipping['brutto'];
317
        $this->View()->sShippingcostsWithTax =  $debugShipping['brutto'];
318
        $this->View()->sShippingcostsNet = $debugShipping['netto'];
319
        $this->View()->sShippingcostsTax = $debugShipping['tax'];
320
        $this->View()->sAmount = $this->basket['AmountWithTaxNumeric'] ;
321
322
        $this->View()->sAmountNet = $this->basket['sAmountNet'];
323
        $this->View()->sAmountTax = $this->basket['sAmountTax'];
324
        $this->View()->assign('sUserData', $userAdditionalArray);
325
        $this->View()->sPayments = $this->plugin->filterPayments($this->admin->sGetPaymentMeans());
326
        $this->View()->sUserLoggedIn = $this->isUserLoggedIn();
327
    }
328
329
    /**
330
     * Add voucher to cart
331
     *
332
     * At failure view variable sVoucherError will give further information
333
     * At success return to cart / confirm view
334
     */
335
    public function addVoucherAction()
336
    {
337
        $basketObj = $this->get('modules')->Basket();
338
        if ($this->Request()->isPost()) {
339
            $voucher = $basketObj->sAddVoucher($this->Request()->getParam('sVoucher'));
340
            if (!empty($voucher['sErrorMessages'])) {
341
                $this->View()->assign('sVoucherError', $voucher['sErrorMessages'], null, Smarty::SCOPE_ROOT);
342
            }
343
        }
344
        $this->forward('showIframe');
345
    }
346
347
348
349
    /**
350
     * Get shipping costs as an array (brutto / netto) depending on selected country / payment
351
     *
352
     * @return array
353
     */
354
    public function getShippingCosts()
355
    {
356
        $country = $this->getSelectedCountry();
357
        $payment = $this->plugin->getPayment()->getId();
358
        if (empty($country) || empty($payment)) {
359
            return ['brutto' =>0, 'netto' =>0];
360
        }
361
        $shippingcosts = $this->admin->sGetPremiumShippingcosts($country);
362
        return empty($shippingcosts) ? ['brutto' =>0, 'netto' =>0] : $shippingcosts;
363
    }
364
365
    /**
366
     * Express Iframe Test
367
     */
368
    public function finishAction()
369
    {
370
        $connector = $this->plugin->getConnector();
371
        $klarnaOrder = new Klarna_Checkout_Order($connector, $this->session['KlarnaOrder']);
0 ignored issues
show
Documentation introduced by
$connector is of type object<Klarna_Checkout_Connector>, but the function expects a object<Klarna_Checkout_ConnectorInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
372
        $klarnaOrder->fetch();
373
        $this->View()->loadTemplate("frontend/checkout/finish.tpl");
374
        $this->View()->assign('KlarnaOrder', $klarnaOrder->marshal());
375
        // reset basket
376
        unset($this->session['KlarnaOrder']);
377
        unset($this->session['sBasketQuantity']);
378
        unset($this->session['sBasketAmount']);
379
    }
380
381
    /**
382
     * Change quantity of a certain product
383
     * @param sArticle = The article to update
384
     * @param sQuantity = new quantity
385
     * Forward to cart / confirm view after success
386
     */
387
    public function changeQuantityAction()
388
    {
389
        $basketObj = $this->get('modules')->Basket();
390
391
        if ($this->Request()->getParam('sArticle') && $this->Request()->getParam('sQuantity')) {
392
            $this->View()->sBasketInfo = $basketObj->sUpdateArticle(
393
                $this->Request()->getParam('sArticle'),
394
                $this->Request()->getParam('sQuantity')
395
            );
396
        }
397
        $this->redirect(['action' => $this->Request()->getParam('sTargetAction', 'showIframe')]);
398
    }
399
400
    /**
401
     * Delete an article from cart -
402
     * @param sDelete = id from s_basket identifying the product to delete
403
     * Forward to cart / confirmation page after success
404
     */
405
    public function deleteArticleAction()
406
    {
407
        $basketObj = $this->get('modules')->Basket();
408
409
        if ($this->Request()->getParam('sDelete')) {
410
            $basketObj->sDeleteArticle($this->Request()->getParam('sDelete'));
411
        }
412
        $this->forward($this->Request()->getParam('sTargetAction', 'index'));
413
    }
414
415
    /**
416
     * Get all dispatches available in selected country from sAdmin object
417
     *
418
     * @param null $paymentId
419
     * @return array|boolean list of dispatches
420
     */
421
    public function getDispatches($paymentId = null)
422
    {
423
        $country = $this->getSelectedCountry();
424
        $state = $this->getSelectedState();
425
        if (empty($country)) {
426
            return false;
427
        }
428
        $stateId = !empty($state['id']) ? $state['id'] : null;
429
        return $this->admin->sGetPremiumDispatches($country['id'], $paymentId, $stateId);
430
    }
431
432
    /**
433
     * Set the provided dispatch method
434
     *
435
     * @param int $dispatchId ID of the dispatch method to set
436
     * @param int|null $paymentId Payment id to validate
437
     * @return int set dispatch method id
438
     */
439
    public function setDispatch($dispatchId, $paymentId = null)
440
    {
441
        $supportedDispatches = $this->getDispatches($paymentId);
442
443
        // Iterate over supported dispatches, look for the provided one
444
        foreach ($supportedDispatches as $dispatch) {
0 ignored issues
show
Bug introduced by
The expression $supportedDispatches of type array|boolean is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
445
            if ($dispatch['id'] == $dispatchId) {
446
                $this->session['sDispatch'] = $dispatchId;
447
                return $dispatchId;
448
            }
449
        }
450
451
        // If it was not found, we fallback to the default (head of supported)
452
        $defaultDispatch = array_shift($supportedDispatches);
453
        $this->session['sDispatch'] = $defaultDispatch['id'];
454
        return $this->session['sDispatch'];
455
    }
456
457
    /**
458
     * Get selected dispatch or select a default dispatch
459
     *
460
     * @return boolean|array
461
     */
462
    public function getSelectedDispatch()
463
    {
464
        if (empty($this->session['sCountry'])) {
465
            return false;
466
        }
467
468
        $dispatches = $this->admin->sGetPremiumDispatches($this->session['sCountry'], null, $this->session['sState']);
469
        if (empty($dispatches)) {
470
            unset($this->session['sDispatch']);
471
            return false;
472
        }
473
474
        foreach ($dispatches as $dispatch) {
475
            if ($dispatch['id'] == $this->session['sDispatch']) {
476
                return $dispatch;
477
            }
478
        }
479
        $dispatch = reset($dispatches);
480
        $this->session['sDispatch'] = (int) $dispatch['id'];
481
        return $dispatch;
482
    }
483
484
    /**
485
     * On any change on country, payment or dispatch recalculate shipping costs
486
     * and forward to cart / confirm view
487
     */
488
    public function calculateShippingCostsAction()
489
    {
490
        if ($this->Request()->getPost('sCountry')) {
491
            $this->session['sCountry'] = (int) $this->Request()->getPost('sCountry');
492
            $this->session["sState"] = 0;
493
            $this->session["sArea"] = Shopware()->Db()->fetchOne("
494
            SELECT areaID FROM s_core_countries WHERE id = ?
495
            ", [$this->session['sCountry']]);
496
        }
497
498
        if ($this->Request()->getPost('sPayment')) {
499
            $this->session['sPaymentID'] = (int) $this->Request()->getPost('sPayment');
500
        }
501
502
        if ($this->Request()->getPost('sDispatch')) {
503
            $this->session['sDispatch'] = (int) $this->Request()->getPost('sDispatch');
504
        }
505
506
        if ($this->Request()->getPost('sState')) {
507
            $this->session['sState'] = (int) $this->Request()->getPost('sState');
508
        }
509
510
        // We might change the shop context here so we need to initialize it again
511
        $this->get('shopware_storefront.context_service')->initializeShopContext();
512
513
        // We need an indicator in the view to expand the shipping costs pre-calculation on page load
514
        $this->View()->assign('calculateShippingCosts', true);
515
516
        $this->forward('showIframe');
517
    }
518
519
    /**
520
     * Get current selected country - if no country is selected, choose first one from list
521
     * of available countries
522
     *
523
     * @return array with country information
524
     */
525
    public function getSelectedCountry()
526
    {
527
        if (!empty($this->View()->sUserData['additional']['countryShipping'])) {
528
            $this->session['sCountry'] = (int) $this->View()->sUserData['additional']['countryShipping']['id'];
529
            $this->session['sArea'] = (int) $this->View()->sUserData['additional']['countryShipping']['areaID'];
530
531
            return $this->View()->sUserData['additional']['countryShipping'];
532
        }
533
        $countries = $this->getCountryList();
534
        if (empty($countries)) {
535
            unset($this->session['sCountry']);
536
            return false;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return false; (false) is incompatible with the return type documented by Shopware_Controllers_Fro...rna::getSelectedCountry of type array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
537
        }
538
        $country = reset($countries);
539
        $this->session['sCountry'] = (int) $country['id'];
540
        $this->session['sArea'] = (int) $country['areaID'];
541
        $this->View()->sUserData['additional']['countryShipping'] = $country;
542
        return $country;
543
    }
544
545
    /**
546
     * Get all countries from database via sAdmin object
547
     *
548
     * @return array list of countries
549
     */
550
    public function getCountryList()
551
    {
552
        return $this->admin->sGetCountryList();
553
    }
554
555
    /**
556
     * Get current selected country - if no country is selected, choose first one from list
557
     * of available countries
558
     *
559
     * @return array with country information
560
     */
561
    public function getSelectedState()
562
    {
563
        if (!empty($this->View()->sUserData['additional']['stateShipping'])) {
564
            $this->session['sState'] = (int) $this->View()->sUserData['additional']['stateShipping']['id'];
565
            return $this->View()->sUserData['additional']['stateShipping'];
566
        }
567
        return ["id" => $this->session['sState']];
568
    }
569
570
    /**
571
     * @param Klarna_Checkout_Order $order
0 ignored issues
show
Documentation introduced by
Should the type for parameter $order not be Klarna_Checkout_Order|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
572
     * @param bool $checkLoginState
573
     */
574
    public function createAccount($order = null, $checkLoginState = true)
575
    {
576
        $this->plugin->klarnaLog('Entering Shopware_Controllers_Frontend_PaymentKlarna::createAccount', 3);
577
        $module = Shopware()->Modules()->Admin();
578
        $session = Shopware()->Session();
579
        $version = Shopware()->Config()->version;
580
581
        if ($version == '___VERSION___' || version_compare($version, '4.1.0', '>=')) {
582
            $encoder = Shopware()->PasswordEncoder()->getDefaultPasswordEncoderName();
583
        }
584
        
585
        $data = [];
586
587
        if ($order !== null && !empty($order['billing_address']['email'])) {
588
            $data['auth']['email'] = $order['billing_address']['email'];
589
            $data['auth']['password'] = $order['reference'];
590
        } else {
591
            $sessionId = Shopware()->SessionID();
592
            // email is only varchar(70) so we cut the sessionid
593
            //$sessionId = substr($sessionId, 0,49);
0 ignored issues
show
Unused Code Comprehensibility introduced by
65% 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...
594
            $data['auth']['email'] = substr($sessionId, 0, 49) . '@klarna.com';
595
            $data['auth']['password'] = $sessionId;
596
        }
597
        $data['auth']['accountmode'] = '1';
598
599
        $phone = $order['billing_address']['phone'];
600
        $data['billing']['phone'] = !empty($phone) ? $phone : ' ';
601
        $data['phone'] = !empty($phone) ? $phone : ' ';
602
        if (!empty($order['customer']['date_of_birth'])) {
603
            list($data['billing']['birthyear'], $data['billing']['birthmonth'], $data['billing']['birthday']) = explode(
604
                '-',
605
                $order['customer']['date_of_birth']
606
            );
607
        }
608
609
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->order:", 4, $order);
610
        
611
        foreach (['billing', 'shipping'] as $type) {
612
            if (isset($order[$type . '_address'])) {
613
                $orderAddress = $order[$type . '_address'];
614
                if (isset($orderAddress['title'])) {
615
                    $data[$type]['salutation'] = $orderAddress['title'] == 'Frau' ? 'ms' : 'mr';
616
                } else {
617
                    $data[$type]['salutation'] = 'mr';
618
                }
619
                $data[$type]['firstname'] = $orderAddress['given_name'];
620
                $data[$type]['lastname'] = $orderAddress['family_name'];
621
                if (isset($orderAddress['street_name']) && $orderAddress['street_number']) {
622
                    if (version_compare(Shopware::VERSION, '5.0.0', '>=')) {
623
                        $data[$type]['street'] = $orderAddress['street_name'] . ' ' . $orderAddress['street_number'];
624 View Code Duplication
                    } else {
625
                        $data[$type]['street'] = $orderAddress['street_name'];
626
                        $data[$type]['streetnumber'] = $orderAddress['street_number'];
627
                    }
628
                } else {
629
                    $data[$type]['street'] = $orderAddress['street_address'];
630
                    $data[$type]['streetnumber'] = ' ';
631
                }
632
                $data[$type]['zipcode'] = $orderAddress['postal_code'];
633
                $data[$type]['city'] = $orderAddress['city'];
634
                if (!empty($orderAddress['care_of'])) {
635
                    if ($orderAddress['street_name'] == 'Packstation') {
636
                        $data[$type]['postnumber'] = $orderAddress['care_of'];
637
                        $data[$type]['swagDhlPostnumber'] = $data[$type]['postnumber'];
638
                    } else {
639
                        $data[$type]['company'] = $orderAddress['care_of'];
640
                    }
641
                }
642
            }
643
644
            if (!isset($data[$type]['company'])) {
645
                $data[$type]['company'] = '';
646
            }
647
            $data[$type]['department'] = '';
648
649
            if (!empty($order[$type . '_address']['country'])) {
650
                $sql = 'SELECT id FROM s_core_countries WHERE countryiso=?';
651
                $countryId = Shopware()->Db()->fetchOne($sql, [$order[$type . '_address']['country']]);
652
            } else {
653
                $countryId = $session['sCountry'];
654
            }
655
            // make sure country is set in case of lost sessions defualt to germany
656
            if (empty($countryId)) {
657
                $countryId = 2;
658
            }
659
660
            $data[$type]['country'] = $countryId;
661
        }
662
663
        $this->plugin->klarnaLog(
664
            "Shopware_Controllers_Frontend_PaymentKlarna::createAccount->data AFTER ADDRESSES:",
665
            4,
666
            $data
667
        );
668
        $sql = 'SELECT id FROM s_core_paymentmeans WHERE name=?';
669
        $paymentId = Shopware()->Db()->fetchOne($sql, ['klarna_checkout']);
670
671
        if ($order !== null && !empty($order['billing_address']['email'])) {
672
            $shop = $this->get('shop');
673
            $shop = $shop->getMain() ?: $shop;
674
            $sql = 'SELECT id, email, `password` FROM `s_user` WHERE `email` LIKE ? AND `active` = 1 ';
675
            if ($shop->getCustomerScope()) {
676
                $sql .= "AND `subshopID` = {$shop->getId()} ";
677
            }
678
            $sql .= 'ORDER BY `accountmode`';
679
            $user = Shopware()->Db()->fetchRow($sql, [$data['auth']['email']]);
680
            // First try login
681
            if (!empty($user)) {
682
                $session->offsetSet('sUserMail', $user['email']);
683
                $session->offsetSet('sUserPassword', $user['password']);
684
                $session->offsetSet('sUserId', $user['id']);
685
            } else {
686
                $this->plugin->klarnaLog(
687
                    "Shopware_Controllers_Frontend_PaymentKlarna::createAccount->user Not Found in DB SQL was:" . $sql,
688
                    1
689
                );
690
            }
691
        }
692
693
        if ($checkLoginState) {
694
            // Check login status
695
            if (!empty($session->sUserId)) {
696
                if ($order !== null) {
697
                    $module->sSYSTEM->_POST = $data['shipping'];
698
                    if ($this->plugin->isShopwareVersionNew()) {
699
                        $userId = $session->offsetGet('sUserId');
700
                        $this->updateShipping($userId, $data['shipping']);
701
                    } else {
702
                        $module->sUpdateShipping();
703
                    }
704
                    $module->sSYSTEM->_POST = $data['billing'];
705
                    if ($this->plugin->isShopwareVersionNew()) {
706
                         $userId = $session->offsetGet('sUserId');
707
                         $this->updateBilling($userId, $data['billing']);
708
                    } else {
709
                        $module->sUpdateBilling();
710
                    }
711
                    unset($data['auth']['password']);
712
                    $module->sSYSTEM->_POST = $data['auth'];
713
                    if ($this->plugin->isShopwareVersionNew()) {
714
                        $userId = $session->offsetGet('sUserId');
715
                        $this->updateCustomer($data, $userId);
716
                        $this->plugin->klarnaLog(
717
                            "Shopware_Controllers_Frontend_PaymentKlarna::createAccount->updateCustomer:",
718
                            3,
719
                            $data
720
                        );
721
                    } else {
722
                        $module->sUpdateAccount();
723
                        $this->plugin->klarnaLog(
724
                            "Shopware_Controllers_Frontend_PaymentKlarna::createAccount->updateAccount:",
725
                            3,
726
                            $this->front->Request()->getPost()
727
                        );
728
                    }
729
                } else {
730
                    /** @var Enlight_Controller_Front $front */
731
                    $front = $this->get('front');
732
                    $front->Request()->setPost([]);
733
                    $module->sSYSTEM->_POST = ['country' => $data['shipping']['country']];
734
                    $shippingId = $this->get('db')->fetchOne(
735
                        'SELECT id FROM s_user_shippingaddress WHERE userID = ?',
736
                        [$session->offsetGet('sUserId')]
737
                    );
738
                    if (!empty($shippingId)) {
739
                        if (Shopware::VERSION === '___VERSION___' ||
740
                            version_compare(Shopware::VERSION, '5.2.0', '>=')
741
                        ) {
742
                            $userId = $session->offsetGet('sUserId');
743
                            $this->updateShipping($userId, $data['shipping']);
744
                        } else {
745
                            $module->sUpdateShipping();
746
                        }
747
                    } else {
748
                        $module->sUpdateBilling();
749
                    }
750
                }
751
                $module->sSYSTEM->_POST = ['sPayment' => $paymentId];
752
                $module->sUpdatePayment();
753
            } else {
754
                $data['payment']['object'] = $module->sGetPaymentMeanById($paymentId);
755
                if (isset($encoder)) {
756
                    $data["auth"]["encoderName"] = $encoder;
757
                    $data["auth"]["password"] = Shopware()->PasswordEncoder()
758
                        ->encodePassword($data["auth"]["password"], $encoder);
759
                } else {
760
                    $data['auth']['password'] = md5($data['auth']['password']);
761
                }
762
                $session->sRegisterFinished = false;
763
                if (version_compare(Shopware::VERSION, '4.3.0', '>=') &&
764
                    version_compare(Shopware::VERSION, '5.2.0', '<')
765
                ) {
766
                    $session->sRegister = $data;
767
                } elseif (version_compare(Shopware::VERSION, '4.3.0', '<')) {
768
                    $session->sRegister = new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS);
769
                }
770
                try {
771
                    if ($this->plugin->isShopwareVersionNew()) {
772
                        $newdata = $this->saveUser($data);
773
                        $module->sSYSTEM->_POST = $newdata['auth'];
774
                        $errors = $module->sLogin(true);
0 ignored issues
show
Unused Code introduced by
$errors is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
775
                        $this->plugin->klarnaLog(
776
                            "Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser:",
777
                            3,
778
                            $newdata
779
                        );
780
                    } else {
781
                        $this->plugin->klarnaLog(
782
                            "Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser->Register:",
783
                            3,
784
                            $session->sRegister
785
                        );
786
                        $module->sSaveRegister();
787
                        $this->plugin->klarnaLog(
788
                            "Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser->RegisterFinished:",
789
                            3,
790
                            $session->offsetGet('sRegisterFinished')
791
                        );
792
                    }
793
                } catch (\Exception $ex) { /* do nothing */
794
                    $this->plugin->klarnaLog("ERROR while creating User. Exception information:". $ex->getMessage(), 1);
795
                }
796
            }
797
        }
798
        
799
        $this->plugin->klarnaLog(
800
            "Shopware_Controllers_Frontend_PaymentKlarna::createAccount->data END OF METHOD:",
801
            4,
802
            $data
803
        );
804
    }
805
    
806
    /**
807
     * Saves a new user to the system.
808
     *
809
     * @param array $data
810
     * @return array $data
811
     */
812
    private function saveUser($data)
813
    {
814
815 View Code Duplication
        if (empty($data['billing']['birthyear']) ||
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
816
            empty($data['billing']['birthmonth']) ||
817
            empty($data['billing']['birthday'])
818
        ) {
819
            $data['birthdate'] = null;
820
        } else {
821
            $data['birthdate'] = $data['billing']['birthyear'] . '-' .
822
                $data['billing']['birthmonth'] . '-' . $data['billing']['birthday'];
823
            $data['birthday'] = $data['birthdate'];
824
        }
825
826
        $plainbilling = array_merge($data['auth'], $data['billing']);
827
        $plainshipping = array_merge($data['auth'], $data['shipping']);
828
829
        //Create forms and validate the input
830
        $customer = new Shopware\Models\Customer\Customer();
831
832
        $customer->setBirthday($data['birthdate']);
833
834
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\PersonalFormType', $customer);
835
        $form->submit($plainbilling);
836
837
        $billingaddress = new Shopware\Models\Customer\Address();
838
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\AddressFormType', $billingaddress);
839
        $form->submit($plainbilling);
840
841
        $shippingaddress = new Shopware\Models\Customer\Address();
842
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\AddressFormType', $shippingaddress);
843
        $form->submit($plainshipping);
844
845
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface $context */
846
        $context = $this->get('shopware_storefront.context_service')->getShopContext();
847
848
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\Shop $shop */
849
        $shop = $context->getShop();
850
851
        /** @var Shopware\Bundle\AccountBundle\Service\RegisterServiceInterface $registerService */
852
        $registerService = $this->get('shopware_account.register_service');
853
        $registerService->register($shop, $customer, $billingaddress, $shippingaddress);
854
855
        // get updated password; it is md5 randomized after register
856
        $getUser = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
857
            ['email' =>  $data['auth']['email']]
858
        );
859
860
        $data['auth']['password'] = $getUser->getPassword();
861
        $data['auth']['passwordMD5'] = $getUser->getPassword();
862
        $data['auth']['encoderName'] = 'md5';
863
864
        return $data;
865
    }
866
867
868
    /**
869
     * Endpoint for changing the main profile data
870
     */
871
    public function updateCustomer($data, $userId)
872
    {
873 View Code Duplication
        if (empty($data['billing']['birthyear']) ||
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
874
            empty($data['billing']['birthmonth']) ||
875
            empty($data['billing']['birthday'])
876
        ) {
877
            $data['birthdate'] = "0000-00-00";
878
        } else {
879
            $data['birthdate'] = $data['billing']['birthyear'] . '-' .
880
                $data['billing']['birthmonth'] . '-' . $data['billing']['birthday'];
881
            $data['birthday'] = $data['birthdate'];
882
        }
883
        $data['email'] = $data['auth']['email'];
884
        $data['firstname'] = $data['billing']['firstname'];
885
        $data['lastname'] = $data['billing']['lastname'];
886
        unset($data['shipping']);
887
        unset($data['billing']);
888
889
        $customer = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
890
            ['id' =>  $userId]
891
        );
892
        $customer->fromArray($data);
893
        Shopware()->Container()->get('shopware_account.customer_service')->update($customer);
894
    }
895
896
897
     /**
898
     * Updates the shipping address
899
     *
900
     * @param int $userId
901
     * @param array $shippingData
902
     */
903
    private function updateShipping($userId, $shippingData)
904
    {
905
        /** @var \Shopware\Components\Model\ModelManager $em */
906
        $em = $this->get('models');
907
908
        /** @var \Shopware\Models\Customer\Customer $customer */
909
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(['id' => $userId]);
910
911
        /** @var \Shopware\Models\Customer\Address $address */
912
        $addressold = $customer->getDefaultShippingAddress();
913
        $address = new \Shopware\Models\Customer\Address();
914
        
915
         /** @var \Shopware\Models\Country\Country $country */
916
        $country = $addressold->getCountry();
917
        $shippingData['country'] = $country;
918
        if ($shippingData['phone'] === null) {
919
            $shippingData['phone'] = ' ';
920
        }
921
        $address->fromArray($shippingData);
922
        try {
923
            $addressService = $this->get('shopware_account.address_service');
924
            $addressService->create($address, $customer);
925
            $addressService->setDefaultShippingAddress($address);
926
        } catch (Exception $ex) {
927
            $this->plugin->klarnaLog(
928
                "ERROR while creating address via address service. Exception information:" . $ex->getMessage(),
929
                1
930
            );
931
        }
932
    }
933
934
    /**
935
     * Updates the billing address
936
     *
937
     * @param int $userId
938
     * @param array $billingData
939
     */
940
    private function updateBilling($userId, $billingData)
941
    {
942
        /** @var \Shopware\Components\Model\ModelManager $em */
943
        $em = $this->get('models');
944
945
        /** @var \Shopware\Models\Customer\Customer $customer */
946
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(['id' => $userId]);
947
948
        /** @var \Shopware\Models\Customer\Address $address */
949
        $address = $customer->getDefaultBillingAddress();
950
        
951
         /** @var \Shopware\Models\Country\Country $country */
952
        $country = $address->getCountry();
953
        $billingData['country'] = $country;
954
        $address->fromArray($billingData);
955
956
        $this->get('shopware_account.address_service')->update($address);
957
    }
958
959
960
    /**
961
     * Needed to reset the session when the user logs in
962
     */
963
    public function loginAction()
964
    {
965
        // Shopware()->Session()->offsetSet('KlarnaOrder', null);
0 ignored issues
show
Unused Code Comprehensibility introduced by
71% 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...
966
        $this->redirect(['controller' => 'payment_klarna', 'action' => 'showIframe']);
967
    }
968
969
    /**
970
     * Return action method
971
     *
972
     * Reads the transactionResult and represents it for the customer.
973
     */
974
    public function returnAction()
975
    {
976
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction", 3);
977
        $transactionId = $this->Request()->getParam('transactionId');
978
        $connector = $this->plugin->getConnector();
979
980
        $order = new Klarna_Checkout_Order($connector, $transactionId);
0 ignored issues
show
Documentation introduced by
$connector is of type object<Klarna_Checkout_Connector>, but the function expects a object<Klarna_Checkout_ConnectorInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
981
        $this->plugin->klarnaLog(
982
            "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->transactionId:\n" . $transactionId,
983
            3
984
        );
985
        $this->plugin->klarnaLog(
986
            "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->order:",
987
            4,
988
            $order
989
        );
990
        $orderNumber = '';
991
        $session = Shopware()->Session();
992
993
        // set payment to Klarna Checkout Dangerous??
994
        $session['sPaymentID'] = $this->plugin->getPayment()->getId();
995
996
        try {
997
            $order->fetch();
998
999
            // if already created by pushaction just redirect
1000
1001
            if ($order['status'] === 'created') {
1002
                $this->plugin->klarnaLog(
1003
                    "Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1004
                    "OrderStatus is already created... nothing to do: " . $orderNumber,
1005
                    1
1006
                );
1007
                $this->redirect([
1008
                    'controller' => 'payment_klarna',
1009
                    'action' => 'finish',
1010
                    'sUniqueID' => $order['reference']
1011
                ]);
1012
            }
1013
1014
            $this->createAccount($order);
1015
            // After createAccount update PaymentId to Klarna, could be defaultpayment
1016
            $this->plugin->savePayment($this->plugin->getPayment()->getId());
1017
            Shopware()->Session()->sOrderVariables['sUserData'] = $this->getUserData();
1018
1019 View Code Duplication
            if ($order['status'] == 'checkout_complete') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1020
                $this->plugin->klarnaLog(
1021
                    "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1022
                    "checkout_complete. Save oder if session values match.",
1023
                    3
1024
                );
1025
                if (Shopware()->Session()->offsetGet('KlarnaTransactionId') == null) {
1026
                    $this->plugin->klarnaLog(
1027
                        "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1028
                        "Session matches. Order will be saved",
1029
                        3
1030
                    );
1031
                    Shopware()->Session()->offsetSet('KlarnaTransactionId', $transactionId);
1032
                    $orderNumber = $this->saveOrder(
1033
                        $order['reservation'],
1034
                        $order['reference']
1035
                    );
1036
                    Shopware()->Session()->offsetSet('KlarnaTransactionId', null);
1037
                }
1038
            }
1039
1040
1041 View Code Duplication
            if (empty($orderNumber) && !empty($order['merchant_reference']['orderid1'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1042
                $orderNumber = $order['merchant_reference']['orderid1'];
1043
            }
1044
1045 View Code Duplication
            if (!empty($orderNumber)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1046
                $update = [];
1047
1048
                $update['status'] = 'created';
1049
                $update['merchant_reference'] = [
1050
                    'orderid1' => (string)$orderNumber,
1051
                    'orderid2' => (string)$order['reference']
1052
                ];
1053
                $order->update($update);
1054
            }
1055
           
1056
            // Saves postnumber for dhl packstation
1057
            if (!empty($orderNumber)
1058
                && !empty($order['shipping_address']['care_of'])
1059
                && $order['shipping_address']['street_name'] == 'Packstation'
1060
                && $this->config->get('postnumberField')
1061
            ) {
1062
                $field = $this->config->get('postnumberField');
1063
                $value = $order['shipping_address']['care_of'];
1064
                $this->saveOrderAttribute($orderNumber, $field, $value);
1065
            }
1066
1067
            $session['KlarnaOrder'] = $order->getLocation();
1068
1069
            if ($order['status'] == 'created' || $order['status'] == 'checkout_complete') {
1070
                $this->saveOrderAttribute($orderNumber, 'swag_klarna_status', 'created');
1071
                $this->savePaymentStatus(
1072
                    $order['reservation'],
1073
                    $order['reference'],
1074
                    $this->config->get('statusId')
1075
                );
1076
                $this->redirect([
1077
                    'controller' => 'payment_klarna',
1078
                    'action' => 'finish',
1079
                    'sUniqueID' => $order['reference']
1080
                ]);
1081
            } else {
1082
                $this->redirect(['controller' => 'checkout', 'action' => 'confirm']);
1083
            }
1084
        } catch (Exception $e) {
1085
            Shopware()->Plugins()->Controller()->ViewRenderer()->setNoRender();
1086
            $this->plugin->klarnaLog(
1087
                "Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1088
                "Catch. Searching for Order:",
1089
                3
1090
            );
1091
            $this->checkKlarnaOrderExistsByReservation($order['reservation']);
1092
            $this->checkKlarnaOrderExistsByReference($order['reference']);
1093
            $this->checkKlarnaOrderExistsBySession(Shopware()->Session()->sUserId);
1094
            $this->checkKlarnaOrderDetailsBySession(Shopware()->Session()->sUserId);
1095
            echo "Entschuldigung, Ein Verbindungsfehler ist aufgetreten, bitte aktualisieren Sie die Seite";
1096
            echo $e->getMessage();
1097
        }
1098
    }
1099
    
1100
    /**
1101
     * Method checks if certain klarna order exists or not
1102
     *
1103
     * @param string $sessionID
1104
     * @return bool
1105
     */
1106 View Code Duplication
    protected function checkKlarnaOrderExistsBySession($sessionID)
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...
1107
    {
1108
        $sql = '
1109
            SELECT * FROM s_order
1110
            WHERE userID=?
1111
        ';
1112
        
1113
        $order = Shopware()->Db()->fetchAll($sql, [
1114
                $sessionID
1115
        ]);
1116
        
1117
        $orderExists = (empty($order)) ? false : true;
1118
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession:", 3);
1119
        if ($orderExists) {
1120
            $this->plugin->klarnaLog(
1121
                "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession: Order Found: ",
1122
                3,
1123
                $order
1124
            );
1125
        }
1126
        return $orderExists;
1127
    }
1128
1129
    /**
1130
     * Method checks if certain klarna order exists or not
1131
     *
1132
     * @param string $paymentUniqueId
1133
     * @return bool
1134
     * @internal param string $transactionId
1135
     */
1136 View Code Duplication
    protected function checkKlarnaOrderExistsByReference($paymentUniqueId)
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...
1137
    {
1138
        $sql = '
1139
            SELECT * FROM s_order
1140
            WHERE temporaryID=?
1141
        ';
1142
        
1143
        $order = Shopware()->Db()->fetchAll($sql, [
1144
                $paymentUniqueId
1145
        ]);
1146
        
1147
        $orderExists = (empty($order)) ? false : true;
1148
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference:", 3);
1149
        if ($orderExists) {
1150
            $this->plugin->klarnaLog(
1151
                "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference: Order Found: ",
1152
                3,
1153
                $order
1154
            );
1155
        }
1156
        return $orderExists;
1157
    }
1158
1159
    /**
1160
     * Method checks if certain klarna order exists or not
1161
     *
1162
     * @param string $transactionId
1163
     * @return bool
1164
     * @internal param string $paymentUniqueId
1165
     */
1166 View Code Duplication
    protected function checkKlarnaOrderExistsByReservation($transactionId)
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...
1167
    {
1168
        $sql = '
1169
            SELECT * FROM s_order
1170
            WHERE transactionID=?
1171
        ';
1172
        
1173
        $order = Shopware()->Db()->fetchAll($sql, [
1174
                $transactionId
1175
        ]);
1176
        
1177
        $orderExists = (empty($order)) ? false : true;
1178
        $this->plugin->klarnaLog(
1179
            "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation:",
1180
            3
1181
        );
1182
        if ($orderExists) {
1183
            $this->plugin->klarnaLog(
1184
                "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation: Order Found: ",
1185
                3,
1186
                $order
1187
            );
1188
        }
1189
        return $orderExists;
1190
    }
1191
    
1192
    /**
1193
     * Method checks if certain klarna order exists or not
1194
     *
1195
     * @param string $transactionId
1196
     * @param string $paymentUniqueId
1197
     * @param string $userId
1198
     * @return bool
1199
     */
1200
    protected function checkKlarnaOrderExists($transactionId, $paymentUniqueId, $userId)
1201
    {
1202
        $sql = '
1203
            SELECT ordernumber FROM s_order
1204
            WHERE transactionID=? AND temporaryID=?
1205
            AND status!=-1 AND userID=?
1206
        ';
1207
        
1208
        $orderNumber = Shopware()->Db()->fetchOne($sql, [
1209
                $transactionId,
1210
                $paymentUniqueId,
1211
                $userId
1212
        ]);
1213
        
1214
        $orderExists = (empty($orderNumber)) ? false : true;
1215
        
1216
        return $orderExists;
1217
    }
1218
    
1219
    /**
1220
     * Method checks if certain klarna order exists or not
1221
     *
1222
     * @param string $sessionID
1223
     * @return bool
1224
     */
1225 View Code Duplication
    protected function checkKlarnaOrderDetailsBySession($sessionID)
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...
1226
    {
1227
        $sql = '
1228
            SELECT * FROM s_order
1229
            LEFT JOIN s_order_details ON s_order.id = s_order_details.orderID
1230
            WHERE userID=?
1231
        ';
1232
        
1233
        $orderDetails = Shopware()->Db()->fetchAll($sql, [
1234
                $sessionID
1235
        ]);
1236
        
1237
        $orderExists = (empty($orderDetails)) ? false : true;
1238
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession:", 3);
1239
        if ($orderExists) {
1240
            $this->plugin->klarnaLog(
1241
                "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession: OrderDetails Found: ",
1242
                3,
1243
                $orderDetails
1244
            );
1245
        }
1246
        return $orderExists;
1247
    }
1248
    
1249
    /**
1250
     * Method checks if certain klarna order exists or not
1251
     *
1252
     * @param string $paymentUniqueId
1253
     * @return string
1254
     */
1255
    protected function getUserIdByReference($paymentUniqueId)
1256
    {
1257
        $sql = '
1258
            SELECT userID FROM s_order
1259
            WHERE temporaryID=?
1260
        ';
1261
        
1262
        $userId = Shopware()->Db()->fetchOne($sql, [
1263
                $paymentUniqueId
1264
        ]);
1265
1266
        return $userId;
1267
    }
1268
    
1269
    /**
1270
     *
1271
     *
1272
     * @param string $transactionId
1273
     * @param string $paymentUniqueId
1274
     * @param string $userId
1275
     * @return string $orderNumber
1276
     */
1277 View Code Duplication
    protected function getKlarnaOrderNumber($transactionId, $paymentUniqueId, $userId)
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...
1278
    {
1279
        $sql = '
1280
            SELECT ordernumber FROM s_order
1281
            WHERE transactionID=? AND temporaryID=?
1282
            AND status!=-1 AND userID=?
1283
        ';
1284
1285
        $orderNumber = Shopware()->Db()->fetchOne($sql, [
1286
            $transactionId,
1287
            $paymentUniqueId,
1288
            $userId
1289
        ]);
1290
1291
        return $orderNumber;
1292
    }
1293
1294
    /**
1295
     *
1296
     *
1297
     * @param string $transactionId
1298
     * @param string $paymentUniqueId
1299
     * @param string $userId
1300
     * @return string $orderId
1301
     */
1302 View Code Duplication
    protected function getKlarnaOrderId($transactionId, $paymentUniqueId, $userId)
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...
1303
    {
1304
        $sql = '
1305
            SELECT id FROM s_order
1306
            WHERE transactionID=? AND temporaryID=?
1307
            AND status!=-1 AND userID=?
1308
        ';
1309
1310
        $orderId = Shopware()->Db()->fetchOne($sql, [
1311
            $transactionId,
1312
            $paymentUniqueId,
1313
            $userId
1314
        ]);
1315
1316
        return $orderId;
1317
    }
1318
1319
1320
    /**
1321
     * Notify action method
1322
     */
1323
    public function pushAction()
1324
    {
1325
        $transactionId = $this->Request()->getParam('transactionId');
1326
1327
        $this->plugin->klarnaLog(
1328
            "Shopware_Controllers_Frontend_PaymentKlarna::pushAction->transactionId:\n" . $transactionId,
1329
            3
1330
        );
1331
        $connector = $this->plugin->getConnector();
1332
        $order = new Klarna_Checkout_Order($connector, $transactionId);
0 ignored issues
show
Documentation introduced by
$connector is of type object<Klarna_Checkout_Connector>, but the function expects a object<Klarna_Checkout_ConnectorInterface>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1333
1334
        $order->fetch();
1335
1336
        if ($order['status'] === 'created') {
1337
            $this->plugin->klarnaLog(
1338
                "Shopware_Controllers_Frontend_PaymentKlarna::pushAction: " .
1339
                "OrderStatus is already created... nothing to do: ",
1340
                1
1341
            );
1342
            return;
1343
        }
1344
1345
        $this->createAccount($order);
1346
        // After createAccount update PaymentId to Klarna, could be defaultpayment
1347
        $this->plugin->savePayment($this->plugin->getPayment()->getId());
1348
        Shopware()->Session()->sOrderVariables['sUserData'] = $this->getUserData();
1349
1350 View Code Duplication
        if ($order['status'] == 'checkout_complete') {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1351
            $this->plugin->klarnaLog(
1352
                "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1353
                "checkout_complete. Save oder if session values match.",
1354
                3
1355
            );
1356
            if (Shopware()->Session()->offsetGet('KlarnaTransactionId') == null) {
1357
                $this->plugin->klarnaLog(
1358
                    "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1359
                    "Session matches. Order will be saved",
1360
                    3
1361
                );
1362
                Shopware()->Session()->offsetSet('KlarnaTransactionId', $transactionId);
1363
                $orderNumber = $this->saveOrder(
1364
                    $order['reservation'],
1365
                    $order['reference']
1366
                );
1367
                Shopware()->Session()->offsetSet('KlarnaTransactionId', null);
1368
            }
1369
        }
1370
1371 View Code Duplication
        if (empty($orderNumber) && !empty($order['merchant_reference']['orderid1'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1372
            $orderNumber = $order['merchant_reference']['orderid1'];
1373
        }
1374
1375 View Code Duplication
        if (!empty($orderNumber)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
1376
            $update = [];
1377
1378
            $update['status'] = 'created';
1379
            $update['merchant_reference'] = [
1380
                'orderid1' => (string)$orderNumber,
1381
                'orderid2' => (string)$order['reference']
1382
            ];
1383
            $order->update($update);
1384
        }
1385
1386
        $this->savePaymentStatus(
1387
            $order['reservation'],
1388
            $order['reference'],
1389
            $this->config->get('statusId')
1390
        );
1391
    }
1392
1393
    private function saveOrderAttribute($orderNumber, $field, $value)
1394
    {
1395
        try {
1396
            $sql = "
1397
                INSERT INTO s_order_attributes (orderID, `$field`)
1398
                SELECT id, ? FROM s_order WHERE ordernumber = ?
1399
                ON DUPLICATE KEY UPDATE `$field` = VALUES(`$field`)
1400
            ";
1401
            $this->get('db')->query($sql, [
1402
                $value,
1403
                $orderNumber
1404
            ]);
1405
        } catch (Exception $e) {
1406
            $this->plugin->klarnaLog("PROBLEM SAVING ORDER ATTRIBUTES AFTER KLARNA PUSH!:\n" . $e->getMessage(), 1);
1407
        }
1408
    }
1409
1410
    /**
1411
     * Save register form so we can use it if user change between klarna and register tab
1412
     */
1413
    public function saveFormDataAction()
1414
    {
1415
        $form = $this->Request()->getPost();
1416
1417
        //unset password from passed post
1418
        unset($form['register']['personal']['password']);
1419
1420
        if (!empty($form)) {
1421
            Shopware()->Session()->klarnaSavedRegister = $form;
1422
        }
1423
    }
1424
1425
    /**
1426
     * Helper method to redirect the request to the proper page to set the payment into the customer account
1427
     */
1428
    public function setPaymentAction()
1429
    {
1430
        if ($this->Request()->isPost()) {
1431
            $values = $this->Request()->getPost('register');
1432
            $payment = $values['payment'];
1433
        } else {
1434
            $payment = $this->Request()->getParam('paymentId');
1435
        }
1436
1437
        if (empty($payment)) {
1438
            return;
1439
        }
1440
        $session = Shopware()->Session();
1441
        $session['KlarnaExternalPaymentId'] = $payment;
1442
1443
        $paymentName = $this->getPaymentNameById($session['KlarnaExternalPaymentId']);
1444
        $user = Shopware()->Modules()->Admin()->sGetUserData();
1445
        $userID = $user['additional']['user']['id'];
1446
1447
        // If user is not already registered and has selected external payment method
1448
        // PayPal redirect to PayPal Express checkout to prevent user registration
1449
        if ($paymentName === 'paypal' && empty($userID)) {
1450
            $this->redirect(
1451
                [
1452
                    'controller' => 'payment_paypal',
1453
                    'action'     => 'express',
1454
                ]
1455
            );
1456
        } elseif (empty($userID)) {
1457
            $session->offsetSet('sPaymentID', $payment);
0 ignored issues
show
Bug introduced by
The method offsetSet cannot be called on $session (of type array<string,?,{"KlarnaExternalPaymentId":"?"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1458
            $session->offsetUnset('sUserId');
0 ignored issues
show
Bug introduced by
The method offsetUnset cannot be called on $session (of type array<string,?,{"KlarnaExternalPaymentId":"?"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1459
            $session->offsetSet('sRegisterFinished', false);
0 ignored issues
show
Bug introduced by
The method offsetSet cannot be called on $session (of type array<string,?,{"KlarnaExternalPaymentId":"?"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1460
1461
            $this->redirect(
1462
                [
1463
                    'controller'    => 'register',
1464
                    'action'        => 'index',
1465
                    'sTarget'       => 'checkout',
1466
                    'sTargetAction' => 'confirm',
1467
                ]
1468
            );
1469
        } else {
1470
            $session->offsetSet('sPaymentID', $payment);
0 ignored issues
show
Bug introduced by
The method offsetSet cannot be called on $session (of type array<string,?,{"KlarnaExternalPaymentId":"?"}>).

Methods can only be called on objects. This check looks for methods being called on variables that have been inferred to never be objects.

Loading history...
1471
            $this->plugin->savePayment($payment);
1472
            $this->redirect(
1473
                [
1474
                    'controller' => 'checkout',
1475
                    'action'     => 'confirm',
1476
                ]
1477
            );
1478
        }
1479
    }
1480
1481
    /**
1482
     * This action is called when the user is not logged in and tries to change
1483
     * the payment from klarna to another payment. Only used in responsive theme.
1484
     */
1485
    public function otherPaymentAction()
1486
    {
1487
        $userData = Shopware()->Modules()->Admin()->sGetUserData();
1488
        $session = Shopware()->Session();
1489
1490
        // reset country
1491
        $session['sCountry'] = $userData['additional']['country']['id'];
1492
        unset($session['sChangedCountry']);
1493
1494
        //Register-controller redirects to checkout by default when the user is logged in already.
1495
        /*        $this->redirect(array(
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...
1496
                    'controller' => 'checkout',
1497
                    'action' => 'shippingPayment',
1498
                    'klarnaRedirect' => 1
1499
                    //'sTarget' => 'checkout',
1500
                    //'sTargetAction' => 'shippingPayment'
1501
                ));
1502
        */
1503
        if ($this->isUserLoggedIn()) {
1504
            $this->redirect([
1505
                'controller' => 'checkout',
1506
                'klarnaRedirect' => 1,
1507
                'action' => 'shippingPayment',
1508
                'sTarget' => 'checkout'
1509
            ]);
1510
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
1511
        } else {
1512
            $this->redirect([
1513
                'controller' => 'register',
1514
                'klarnaRedirect' => 1,
1515
                'sTarget' => 'checkout',
1516
                'sTargetAction' => 'shippingPayment'
1517
            ]);
1518
        }
1519
    }
1520
1521
    /**
1522
     * @return bool
1523
     */
1524
    protected function isUserLoggedIn()
1525
    {
1526
         return (isset($this->session->sUserId) && !empty($this->session->sUserId));
1527
    }
1528
1529
    /**
1530
     * Get complete user-data as an array to use in view
1531
     *
1532
     * @return array
1533
     */
1534
    public function getUserData()
1535
    {
1536
        $system = Shopware()->System();
1537
        $admin = Shopware()->Modules()->Admin();
1538
        $userData = $admin->sGetUserData();
1539
        if (!empty($userData['additional']['countryShipping'])) {
1540
            $system->sUSERGROUPDATA = Shopware()->Db()->fetchRow("
1541
                SELECT * FROM s_core_customergroups
1542
                WHERE groupkey = ?
1543
            ", [$system->sUSERGROUP]);
1544
1545
            if ($this->isTaxFreeDelivery($userData)) {
1546
                $system->sUSERGROUPDATA['tax'] = 0;
1547
                $system->sCONFIG['sARTICLESOUTPUTNETTO'] = 1; //Old template
1548
                Shopware()->Session()->sUserGroupData = $system->sUSERGROUPDATA;
1549
                $userData['additional']['charge_vat'] = false;
1550
                $userData['additional']['show_net'] = false;
1551
                Shopware()->Session()->sOutputNet = true;
1552
            } else {
1553
                $userData['additional']['charge_vat'] = true;
1554
                $userData['additional']['show_net'] = !empty($system->sUSERGROUPDATA['tax']);
1555
                Shopware()->Session()->sOutputNet = empty($system->sUSERGROUPDATA['tax']);
1556
            }
1557
        }
1558
1559
        return $userData;
1560
    }
1561
1562
    /**
1563
     * Validates if the provided customer should get a tax free delivery
1564
     * @param array $userData
1565
     * @return bool
1566
     */
1567
    protected function isTaxFreeDelivery($userData)
1568
    {
1569
        if (!empty($userData['additional']['countryShipping']['taxfree'])) {
1570
            return true;
1571
        }
1572
1573
        if (empty($userData['additional']['countryShipping']['taxfree_ustid'])) {
1574
            return false;
1575
        }
1576
1577
        return !empty($userData['shippingaddress']['ustid']);
1578
    }
1579
1580
    /**
1581
     * returns payment name from payment Ids
1582
     * @param integer $paymentId
1583
     * @return string
1584
     */
1585
    private function getPaymentNameById($paymentId)
1586
    {
1587
        $paymentRepo = Shopware()->Models()->getRepository('Shopware\Models\Payment\Payment');
1588
        $payment = $paymentRepo->findOneBy(['id' => $paymentId]);
1589
        return $payment->getName();
1590
    }
1591
}
1592