Completed
Push — master ( 1b9763...313734 )
by Stefan
03:05
created

checkKlarnaOrderExistsByReference()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 12

Duplication

Lines 17
Ratio 77.27 %

Importance

Changes 0
Metric Value
cc 3
eloc 12
c 0
b 0
f 0
nc 4
nop 1
dl 17
loc 22
rs 9.2
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
        $plainbilling = array_merge($data['auth'], $data['billing']);
816
        $plainshipping = array_merge($data['auth'], $data['shipping']);
817
818
        if (empty($plainbilling['birthyear']) ||
819
            empty($plainbilling['birthmonth']) ||
820
            empty($plainbilling['birthday'])
821
        ) {
822
            $plainbilling['birthday'] = null;
823
        } else {
824
            $plainbilling['birthday'] = new \DateTime(
825
               $plainbilling['birthyear'] . '-' .
826
                    $plainbilling['birthmonth'] . '-' .
827
                    $plainbilling['birthday']);
828
        }
829
830
        //Create forms and validate the input
831
        $customer = new Shopware\Models\Customer\Customer();
832
833
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\PersonalFormType', $customer);
834
        $form->submit($plainbilling);
835
836
        $billingaddress = new Shopware\Models\Customer\Address();
837
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\AddressFormType', $billingaddress);
838
        $form->submit($plainbilling);
839
840
        $shippingaddress = new Shopware\Models\Customer\Address();
841
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\AddressFormType', $shippingaddress);
842
        $form->submit($plainshipping);
843
844
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface $context */
845
        $context = $this->get('shopware_storefront.context_service')->getShopContext();
846
847
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\Shop $shop */
848
        $shop = $context->getShop();
849
850
        /** @var Shopware\Bundle\AccountBundle\Service\RegisterServiceInterface $registerService */
851
        $registerService = $this->get('shopware_account.register_service');
852
        $registerService->register($shop, $customer, $billingaddress, $shippingaddress);
853
854
        // get updated password; it is md5 randomized after register
855
        $getUser = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
856
            ['email' =>  $data['auth']['email']]
857
        );
858
859
        $data['auth']['password'] = $getUser->getPassword();
860
        $data['auth']['passwordMD5'] = $getUser->getPassword();
861
        $data['auth']['encoderName'] = 'md5';
862
863
        return $data;
864
    }
865
866
867
    /**
868
     * Endpoint for changing the main profile data
869
     */
870
    public function updateCustomer($data, $userId)
871
    {
872
        if (empty($data['billing']['birthyear']) ||
873
            empty($data['billing']['birthmonth']) ||
874
            empty($data['billing']['birthday'])
875
        ) {
876
            $data['birthdate'] = "0000-00-00";
877
        } else {
878
            $data['birthdate'] = $data['billing']['birthyear'] . '-' .
879
                $data['billing']['birthmonth'] . '-' . $data['billing']['birthday'];
880
            $data['birthday'] = $data['birthdate'];
881
        }
882
        $data['email'] = $data['auth']['email'];
883
        $data['firstname'] = $data['billing']['firstname'];
884
        $data['lastname'] = $data['billing']['lastname'];
885
        unset($data['shipping']);
886
        unset($data['billing']);
887
888
        $customer = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
889
            ['id' =>  $userId]
890
        );
891
        $customer->fromArray($data);
892
        Shopware()->Container()->get('shopware_account.customer_service')->update($customer);
893
    }
894
895
896
     /**
897
     * Updates the shipping address
898
     *
899
     * @param int $userId
900
     * @param array $shippingData
901
     */
902
    private function updateShipping($userId, $shippingData)
903
    {
904
        /** @var \Shopware\Components\Model\ModelManager $em */
905
        $em = $this->get('models');
906
907
        /** @var \Shopware\Models\Customer\Customer $customer */
908
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(['id' => $userId]);
909
910
        /** @var \Shopware\Models\Customer\Address $address */
911
        $addressold = $customer->getDefaultShippingAddress();
912
        $address = new \Shopware\Models\Customer\Address();
913
        
914
         /** @var \Shopware\Models\Country\Country $country */
915
        $country = $addressold->getCountry();
916
        $shippingData['country'] = $country;
917
        if ($shippingData['phone'] === null) {
918
            $shippingData['phone'] = ' ';
919
        }
920
        $address->fromArray($shippingData);
921
        try {
922
            $addressService = $this->get('shopware_account.address_service');
923
            $addressService->create($address, $customer);
924
            $addressService->setDefaultShippingAddress($address);
925
        } catch (Exception $ex) {
926
            $this->plugin->klarnaLog(
927
                "ERROR while creating address via address service. Exception information:" . $ex->getMessage(),
928
                1
929
            );
930
        }
931
    }
932
933
    /**
934
     * Updates the billing address
935
     *
936
     * @param int $userId
937
     * @param array $billingData
938
     */
939
    private function updateBilling($userId, $billingData)
940
    {
941
        /** @var \Shopware\Components\Model\ModelManager $em */
942
        $em = $this->get('models');
943
944
        /** @var \Shopware\Models\Customer\Customer $customer */
945
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(['id' => $userId]);
946
947
        /** @var \Shopware\Models\Customer\Address $address */
948
        $address = $customer->getDefaultBillingAddress();
949
        
950
         /** @var \Shopware\Models\Country\Country $country */
951
        $country = $address->getCountry();
952
        $billingData['country'] = $country;
953
        $address->fromArray($billingData);
954
955
        $this->get('shopware_account.address_service')->update($address);
956
    }
957
958
959
    /**
960
     * Needed to reset the session when the user logs in
961
     */
962
    public function loginAction()
963
    {
964
        // 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...
965
        $this->redirect(['controller' => 'payment_klarna', 'action' => 'showIframe']);
966
    }
967
968
    /**
969
     * Return action method
970
     *
971
     * Reads the transactionResult and represents it for the customer.
972
     */
973
    public function returnAction()
974
    {
975
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction", 3);
976
        $transactionId = $this->Request()->getParam('transactionId');
977
        $connector = $this->plugin->getConnector();
978
979
        $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...
980
        $this->plugin->klarnaLog(
981
            "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->transactionId:\n" . $transactionId,
982
            3
983
        );
984
        $this->plugin->klarnaLog(
985
            "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->order:",
986
            4,
987
            $order
988
        );
989
        $orderNumber = '';
990
        $session = Shopware()->Session();
991
992
        // set payment to Klarna Checkout Dangerous??
993
        $session['sPaymentID'] = $this->plugin->getPayment()->getId();
994
995
        try {
996
            $order->fetch();
997
998
            // if already created by pushaction just redirect
999
1000
            if ($order['status'] === 'created') {
1001
                $this->plugin->klarnaLog(
1002
                    "Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1003
                    "OrderStatus is already created... nothing to do: " . $orderNumber,
1004
                    1
1005
                );
1006
                $this->redirect([
1007
                    'controller' => 'payment_klarna',
1008
                    'action' => 'finish',
1009
                    'sUniqueID' => $order['reference']
1010
                ]);
1011
            }
1012
1013
            $this->createAccount($order);
1014
            // After createAccount update PaymentId to Klarna, could be defaultpayment
1015
            $this->plugin->savePayment($this->plugin->getPayment()->getId());
1016
            Shopware()->Session()->sOrderVariables['sUserData'] = $this->getUserData();
1017
1018 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...
1019
                $this->plugin->klarnaLog(
1020
                    "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1021
                    "checkout_complete. Save oder if session values match.",
1022
                    3
1023
                );
1024
                if (Shopware()->Session()->offsetGet('KlarnaTransactionId') == null) {
1025
                    $this->plugin->klarnaLog(
1026
                        "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1027
                        "Session matches. Order will be saved",
1028
                        3
1029
                    );
1030
                    Shopware()->Session()->offsetSet('KlarnaTransactionId', $transactionId);
1031
                    $orderNumber = $this->saveOrder(
1032
                        $order['reservation'],
1033
                        $order['reference']
1034
                    );
1035
                    Shopware()->Session()->offsetSet('KlarnaTransactionId', null);
1036
                }
1037
            }
1038
1039
1040 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...
1041
                $orderNumber = $order['merchant_reference']['orderid1'];
1042
            }
1043
1044 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...
1045
                $update = [];
1046
1047
                $update['status'] = 'created';
1048
                $update['merchant_reference'] = [
1049
                    'orderid1' => (string)$orderNumber,
1050
                    'orderid2' => (string)$order['reference']
1051
                ];
1052
                $order->update($update);
1053
            }
1054
           
1055
            // Saves postnumber for dhl packstation
1056
            if (!empty($orderNumber)
1057
                && !empty($order['shipping_address']['care_of'])
1058
                && $order['shipping_address']['street_name'] == 'Packstation'
1059
                && $this->config->get('postnumberField')
1060
            ) {
1061
                $field = $this->config->get('postnumberField');
1062
                $value = $order['shipping_address']['care_of'];
1063
                $this->saveOrderAttribute($orderNumber, $field, $value);
1064
            }
1065
1066
            $session['KlarnaOrder'] = $order->getLocation();
1067
1068
            if ($order['status'] == 'created' || $order['status'] == 'checkout_complete') {
1069
                $this->saveOrderAttribute($orderNumber, 'swag_klarna_status', 'created');
1070
                $this->savePaymentStatus(
1071
                    $order['reservation'],
1072
                    $order['reference'],
1073
                    $this->config->get('statusId')
1074
                );
1075
                $this->redirect([
1076
                    'controller' => 'payment_klarna',
1077
                    'action' => 'finish',
1078
                    'sUniqueID' => $order['reference']
1079
                ]);
1080
            } else {
1081
                $this->redirect(['controller' => 'checkout', 'action' => 'confirm']);
1082
            }
1083
        } catch (Exception $e) {
1084
            Shopware()->Plugins()->Controller()->ViewRenderer()->setNoRender();
1085
            $this->plugin->klarnaLog(
1086
                "Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1087
                "Catch. Searching for Order:",
1088
                3
1089
            );
1090
            $this->checkKlarnaOrderExistsByReservation($order['reservation']);
1091
            $this->checkKlarnaOrderExistsByReference($order['reference']);
1092
            $this->checkKlarnaOrderExistsBySession(Shopware()->Session()->sUserId);
1093
            $this->checkKlarnaOrderDetailsBySession(Shopware()->Session()->sUserId);
1094
            echo "Entschuldigung, Ein Verbindungsfehler ist aufgetreten, bitte aktualisieren Sie die Seite";
1095
            echo $e->getMessage();
1096
        }
1097
    }
1098
    
1099
    /**
1100
     * Method checks if certain klarna order exists or not
1101
     *
1102
     * @param string $sessionID
1103
     * @return bool
1104
     */
1105 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...
1106
    {
1107
        $sql = '
1108
            SELECT * FROM s_order
1109
            WHERE userID=?
1110
        ';
1111
        
1112
        $order = Shopware()->Db()->fetchAll($sql, [
1113
                $sessionID
1114
        ]);
1115
        
1116
        $orderExists = (empty($order)) ? false : true;
1117
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession:", 3);
1118
        if ($orderExists) {
1119
            $this->plugin->klarnaLog(
1120
                "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession: Order Found: ",
1121
                3,
1122
                $order
1123
            );
1124
        }
1125
        return $orderExists;
1126
    }
1127
1128
    /**
1129
     * Method checks if certain klarna order exists or not
1130
     *
1131
     * @param string $paymentUniqueId
1132
     * @return bool
1133
     * @internal param string $transactionId
1134
     */
1135 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...
1136
    {
1137
        $sql = '
1138
            SELECT * FROM s_order
1139
            WHERE temporaryID=?
1140
        ';
1141
        
1142
        $order = Shopware()->Db()->fetchAll($sql, [
1143
                $paymentUniqueId
1144
        ]);
1145
        
1146
        $orderExists = (empty($order)) ? false : true;
1147
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference:", 3);
1148
        if ($orderExists) {
1149
            $this->plugin->klarnaLog(
1150
                "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference: Order Found: ",
1151
                3,
1152
                $order
1153
            );
1154
        }
1155
        return $orderExists;
1156
    }
1157
1158
    /**
1159
     * Method checks if certain klarna order exists or not
1160
     *
1161
     * @param string $transactionId
1162
     * @return bool
1163
     * @internal param string $paymentUniqueId
1164
     */
1165 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...
1166
    {
1167
        $sql = '
1168
            SELECT * FROM s_order
1169
            WHERE transactionID=?
1170
        ';
1171
        
1172
        $order = Shopware()->Db()->fetchAll($sql, [
1173
                $transactionId
1174
        ]);
1175
        
1176
        $orderExists = (empty($order)) ? false : true;
1177
        $this->plugin->klarnaLog(
1178
            "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation:",
1179
            3
1180
        );
1181
        if ($orderExists) {
1182
            $this->plugin->klarnaLog(
1183
                "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation: Order Found: ",
1184
                3,
1185
                $order
1186
            );
1187
        }
1188
        return $orderExists;
1189
    }
1190
    
1191
    /**
1192
     * Method checks if certain klarna order exists or not
1193
     *
1194
     * @param string $transactionId
1195
     * @param string $paymentUniqueId
1196
     * @param string $userId
1197
     * @return bool
1198
     */
1199
    protected function checkKlarnaOrderExists($transactionId, $paymentUniqueId, $userId)
1200
    {
1201
        $sql = '
1202
            SELECT ordernumber FROM s_order
1203
            WHERE transactionID=? AND temporaryID=?
1204
            AND status!=-1 AND userID=?
1205
        ';
1206
        
1207
        $orderNumber = Shopware()->Db()->fetchOne($sql, [
1208
                $transactionId,
1209
                $paymentUniqueId,
1210
                $userId
1211
        ]);
1212
        
1213
        $orderExists = (empty($orderNumber)) ? false : true;
1214
        
1215
        return $orderExists;
1216
    }
1217
    
1218
    /**
1219
     * Method checks if certain klarna order exists or not
1220
     *
1221
     * @param string $sessionID
1222
     * @return bool
1223
     */
1224 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...
1225
    {
1226
        $sql = '
1227
            SELECT * FROM s_order
1228
            LEFT JOIN s_order_details ON s_order.id = s_order_details.orderID
1229
            WHERE userID=?
1230
        ';
1231
        
1232
        $orderDetails = Shopware()->Db()->fetchAll($sql, [
1233
                $sessionID
1234
        ]);
1235
        
1236
        $orderExists = (empty($orderDetails)) ? false : true;
1237
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession:", 3);
1238
        if ($orderExists) {
1239
            $this->plugin->klarnaLog(
1240
                "Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession: OrderDetails Found: ",
1241
                3,
1242
                $orderDetails
1243
            );
1244
        }
1245
        return $orderExists;
1246
    }
1247
    
1248
    /**
1249
     * Method checks if certain klarna order exists or not
1250
     *
1251
     * @param string $paymentUniqueId
1252
     * @return string
1253
     */
1254
    protected function getUserIdByReference($paymentUniqueId)
1255
    {
1256
        $sql = '
1257
            SELECT userID FROM s_order
1258
            WHERE temporaryID=?
1259
        ';
1260
        
1261
        $userId = Shopware()->Db()->fetchOne($sql, [
1262
                $paymentUniqueId
1263
        ]);
1264
1265
        return $userId;
1266
    }
1267
    
1268
    /**
1269
     *
1270
     *
1271
     * @param string $transactionId
1272
     * @param string $paymentUniqueId
1273
     * @param string $userId
1274
     * @return string $orderNumber
1275
     */
1276 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...
1277
    {
1278
        $sql = '
1279
            SELECT ordernumber FROM s_order
1280
            WHERE transactionID=? AND temporaryID=?
1281
            AND status!=-1 AND userID=?
1282
        ';
1283
1284
        $orderNumber = Shopware()->Db()->fetchOne($sql, [
1285
            $transactionId,
1286
            $paymentUniqueId,
1287
            $userId
1288
        ]);
1289
1290
        return $orderNumber;
1291
    }
1292
1293
    /**
1294
     *
1295
     *
1296
     * @param string $transactionId
1297
     * @param string $paymentUniqueId
1298
     * @param string $userId
1299
     * @return string $orderId
1300
     */
1301 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...
1302
    {
1303
        $sql = '
1304
            SELECT id FROM s_order
1305
            WHERE transactionID=? AND temporaryID=?
1306
            AND status!=-1 AND userID=?
1307
        ';
1308
1309
        $orderId = Shopware()->Db()->fetchOne($sql, [
1310
            $transactionId,
1311
            $paymentUniqueId,
1312
            $userId
1313
        ]);
1314
1315
        return $orderId;
1316
    }
1317
1318
1319
    /**
1320
     * Notify action method
1321
     */
1322
    public function pushAction()
1323
    {
1324
        $transactionId = $this->Request()->getParam('transactionId');
1325
1326
        $this->plugin->klarnaLog(
1327
            "Shopware_Controllers_Frontend_PaymentKlarna::pushAction->transactionId:\n" . $transactionId,
1328
            3
1329
        );
1330
        $connector = $this->plugin->getConnector();
1331
        $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...
1332
1333
        $order->fetch();
1334
1335
        if ($order['status'] === 'created') {
1336
            $this->plugin->klarnaLog(
1337
                "Shopware_Controllers_Frontend_PaymentKlarna::pushAction: " .
1338
                "OrderStatus is already created... nothing to do: ",
1339
                1
1340
            );
1341
            return;
1342
        }
1343
1344
        $this->createAccount($order);
1345
        // After createAccount update PaymentId to Klarna, could be defaultpayment
1346
        $this->plugin->savePayment($this->plugin->getPayment()->getId());
1347
        Shopware()->Session()->sOrderVariables['sUserData'] = $this->getUserData();
1348
1349 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...
1350
            $this->plugin->klarnaLog(
1351
                "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1352
                "checkout_complete. Save oder if session values match.",
1353
                3
1354
            );
1355
            if (Shopware()->Session()->offsetGet('KlarnaTransactionId') == null) {
1356
                $this->plugin->klarnaLog(
1357
                    "Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: " .
1358
                    "Session matches. Order will be saved",
1359
                    3
1360
                );
1361
                Shopware()->Session()->offsetSet('KlarnaTransactionId', $transactionId);
1362
                $orderNumber = $this->saveOrder(
1363
                    $order['reservation'],
1364
                    $order['reference']
1365
                );
1366
                Shopware()->Session()->offsetSet('KlarnaTransactionId', null);
1367
            }
1368
        }
1369
1370 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...
1371
            $orderNumber = $order['merchant_reference']['orderid1'];
1372
        }
1373
1374 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...
1375
            $update = [];
1376
1377
            $update['status'] = 'created';
1378
            $update['merchant_reference'] = [
1379
                'orderid1' => (string)$orderNumber,
1380
                'orderid2' => (string)$order['reference']
1381
            ];
1382
            $order->update($update);
1383
        }
1384
1385
        $this->savePaymentStatus(
1386
            $order['reservation'],
1387
            $order['reference'],
1388
            $this->config->get('statusId')
1389
        );
1390
    }
1391
1392
    private function saveOrderAttribute($orderNumber, $field, $value)
1393
    {
1394
        try {
1395
            $sql = "
1396
                INSERT INTO s_order_attributes (orderID, `$field`)
1397
                SELECT id, ? FROM s_order WHERE ordernumber = ?
1398
                ON DUPLICATE KEY UPDATE `$field` = VALUES(`$field`)
1399
            ";
1400
            $this->get('db')->query($sql, [
1401
                $value,
1402
                $orderNumber
1403
            ]);
1404
        } catch (Exception $e) {
1405
            $this->plugin->klarnaLog("PROBLEM SAVING ORDER ATTRIBUTES AFTER KLARNA PUSH!:\n" . $e->getMessage(), 1);
1406
        }
1407
    }
1408
1409
    /**
1410
     * Save register form so we can use it if user change between klarna and register tab
1411
     */
1412
    public function saveFormDataAction()
1413
    {
1414
        $form = $this->Request()->getPost();
1415
1416
        //unset password from passed post
1417
        unset($form['register']['personal']['password']);
1418
1419
        if (!empty($form)) {
1420
            Shopware()->Session()->klarnaSavedRegister = $form;
1421
        }
1422
    }
1423
1424
    /**
1425
     * Helper method to redirect the request to the proper page to set the payment into the customer account
1426
     */
1427
    public function setPaymentAction()
1428
    {
1429
        if ($this->Request()->isPost()) {
1430
            $values = $this->Request()->getPost('register');
1431
            $payment = $values['payment'];
1432
        } else {
1433
            $payment = $this->Request()->getParam('paymentId');
1434
        }
1435
1436
        if (empty($payment)) {
1437
            return;
1438
        }
1439
        $session = Shopware()->Session();
1440
        $session['KlarnaExternalPaymentId'] = $payment;
1441
1442
        $paymentName = $this->getPaymentNameById($session['KlarnaExternalPaymentId']);
1443
        $user = Shopware()->Modules()->Admin()->sGetUserData();
1444
        $userID = $user['additional']['user']['id'];
1445
1446
        // If user is not already registered and has selected external payment method
1447
        // PayPal redirect to PayPal Express checkout to prevent user registration
1448
        if ($paymentName === 'paypal' && empty($userID)) {
1449
            $this->redirect(
1450
                [
1451
                    'controller' => 'payment_paypal',
1452
                    'action'     => 'express',
1453
                ]
1454
            );
1455
        } elseif (empty($userID)) {
1456
            $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...
1457
            $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...
1458
            $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...
1459
1460
            $this->redirect(
1461
                [
1462
                    'controller'    => 'register',
1463
                    'action'        => 'index',
1464
                    'sTarget'       => 'checkout',
1465
                    'sTargetAction' => 'confirm',
1466
                ]
1467
            );
1468
        } else {
1469
            $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...
1470
            $this->plugin->savePayment($payment);
1471
            $this->redirect(
1472
                [
1473
                    'controller' => 'checkout',
1474
                    'action'     => 'confirm',
1475
                ]
1476
            );
1477
        }
1478
    }
1479
1480
    /**
1481
     * This action is called when the user is not logged in and tries to change
1482
     * the payment from klarna to another payment. Only used in responsive theme.
1483
     */
1484
    public function otherPaymentAction()
1485
    {
1486
        $userData = Shopware()->Modules()->Admin()->sGetUserData();
1487
        $session = Shopware()->Session();
1488
1489
        // reset country
1490
        $session['sCountry'] = $userData['additional']['country']['id'];
1491
        unset($session['sChangedCountry']);
1492
1493
        //Register-controller redirects to checkout by default when the user is logged in already.
1494
        /*        $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...
1495
                    'controller' => 'checkout',
1496
                    'action' => 'shippingPayment',
1497
                    'klarnaRedirect' => 1
1498
                    //'sTarget' => 'checkout',
1499
                    //'sTargetAction' => 'shippingPayment'
1500
                ));
1501
        */
1502
        if ($this->isUserLoggedIn()) {
1503
            $this->redirect([
1504
                'controller' => 'checkout',
1505
                'klarnaRedirect' => 1,
1506
                'action' => 'shippingPayment',
1507
                'sTarget' => 'checkout'
1508
            ]);
1509
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
1510
        } else {
1511
            $this->redirect([
1512
                'controller' => 'register',
1513
                'klarnaRedirect' => 1,
1514
                'sTarget' => 'checkout',
1515
                'sTargetAction' => 'shippingPayment'
1516
            ]);
1517
        }
1518
    }
1519
1520
    /**
1521
     * @return bool
1522
     */
1523
    protected function isUserLoggedIn()
1524
    {
1525
         return (isset($this->session->sUserId) && !empty($this->session->sUserId));
1526
    }
1527
1528
    /**
1529
     * Get complete user-data as an array to use in view
1530
     *
1531
     * @return array
1532
     */
1533
    public function getUserData()
1534
    {
1535
        $system = Shopware()->System();
1536
        $admin = Shopware()->Modules()->Admin();
1537
        $userData = $admin->sGetUserData();
1538
        if (!empty($userData['additional']['countryShipping'])) {
1539
            $system->sUSERGROUPDATA = Shopware()->Db()->fetchRow("
1540
                SELECT * FROM s_core_customergroups
1541
                WHERE groupkey = ?
1542
            ", [$system->sUSERGROUP]);
1543
1544
            if ($this->isTaxFreeDelivery($userData)) {
1545
                $system->sUSERGROUPDATA['tax'] = 0;
1546
                $system->sCONFIG['sARTICLESOUTPUTNETTO'] = 1; //Old template
1547
                Shopware()->Session()->sUserGroupData = $system->sUSERGROUPDATA;
1548
                $userData['additional']['charge_vat'] = false;
1549
                $userData['additional']['show_net'] = false;
1550
                Shopware()->Session()->sOutputNet = true;
1551
            } else {
1552
                $userData['additional']['charge_vat'] = true;
1553
                $userData['additional']['show_net'] = !empty($system->sUSERGROUPDATA['tax']);
1554
                Shopware()->Session()->sOutputNet = empty($system->sUSERGROUPDATA['tax']);
1555
            }
1556
        }
1557
1558
        return $userData;
1559
    }
1560
1561
    /**
1562
     * Validates if the provided customer should get a tax free delivery
1563
     * @param array $userData
1564
     * @return bool
1565
     */
1566
    protected function isTaxFreeDelivery($userData)
1567
    {
1568
        if (!empty($userData['additional']['countryShipping']['taxfree'])) {
1569
            return true;
1570
        }
1571
1572
        if (empty($userData['additional']['countryShipping']['taxfree_ustid'])) {
1573
            return false;
1574
        }
1575
1576
        return !empty($userData['shippingaddress']['ustid']);
1577
    }
1578
1579
    /**
1580
     * returns payment name from payment Ids
1581
     * @param integer $paymentId
1582
     * @return string
1583
     */
1584
    private function getPaymentNameById($paymentId)
1585
    {
1586
        $paymentRepo = Shopware()->Models()->getRepository('Shopware\Models\Payment\Payment');
1587
        $payment = $paymentRepo->findOneBy(['id' => $paymentId]);
1588
        return $payment->getName();
1589
    }
1590
}
1591