Passed
Push — master ( ad9d2a...3a231c )
by Mario
02:53
created

saveUser()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 35
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 35
rs 8.8571
c 0
b 0
f 0
eloc 19
nc 1
nop 1
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
    /**
21
     * {@inheritdoc}
22
     */
23
    public function preDispatch()
24
    {
25
        $this->plugin = $this->get('plugins')->Frontend()->SwagPaymentKlarna();
26
        $this->config = $this->plugin->Config();
27
        if (in_array($this->Request()->getActionName(), array('push', 'saveFormData'))) {
28
            $this->Front()->Plugins()->ViewRenderer()->setNoRender();
29
        }
30
    }
31
    
32
    /**
33
     * whitelists indexAction for SW 5.2 compatibility
34
     */
35
    public function getWhitelistedCSRFActions()
36
    {
37
        return [
38
            'index',
39
            'express',
40
            'push',
41
            'login',
42
            'return',
43
        ];
44
    }    
45
46
    /**
47
     * {@inheritdoc}
48
     */
49 View Code Duplication
    public function get($name)
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...
50
    {
51
        if (version_compare(Shopware::VERSION, '4.2.0', '<') && Shopware::VERSION != '___VERSION___') {
52
            if ($name == 'pluginlogger') {
53
                $name = 'log';
54
            }
55
            $name = ucfirst($name);
56
            return Shopware()->Bootstrap()->getResource($name);
57
        }
58
        return parent::get($name);
59
    }
60
    
61
    /**
62
     * Index action method.
63
     *
64
     * Forwards to correct the action.
65
     */
66
    public function indexAction()
67
    {
68
        $this->redirect(array('controller' => 'checkout', 'action' => 'confirm'));
69
    }
70
71
    /**
72
     * Express payment action method.
73
     */
74
    public function expressAction()
75
    {
76
        $session = Shopware()->Session();
77
        
78
        if (!empty($session->PaypalResponse)){
79
            $this->plugin->klarnaLog("Paypal Payment in Progress detected Redirecting To Index Page", 3);
80
            $this->redirect(
81
                array(
82
                    'controller' => 'index',
83
                    'action' => 'index'
84
                )
85
            );
86
            return;
87
        }        
88
        
89
        if ($this->Request()->getPost('sCountry')) {
90
            $session['sCountry'] = (int)$this->Request()->getPost('sCountry');
91
            $session["sState"] = 0;
92
            $session["sArea"] = Shopware()->Db()->fetchOne("
93
                SELECT areaID FROM s_core_countries WHERE id = ?
94
            ", array($session['sCountry']));
95
            unset($session->KlarnaOrder);
96
            $session['sChangedCountry'] = (int)$this->Request()->getPost('sCountry');
97
        }
98
        
99
        if (!$this->isUserLoggedIn($session)){
100
	        $this->createAccount();
101
	}
102
        
103
        $user = Shopware()->Modules()->Admin()->sGetUserData();
104
        if ($this->Request()->getPost('sCountry')) {
105
          $session['sCountry'] = $this->Request()->getPost('sCountry'); 
106
          $session['sChangedCountry'] = $this->Request()->getPost('sCountry'); 
107
        }
108
109
        // Switch Paymentmean to Klarna Checkout
110
        $sql = 'SELECT id FROM s_core_paymentmeans WHERE name=?';
111
        $paymentId = Shopware()->Db()->fetchOne($sql, array('klarna_checkout'));
112
        $this->savePayment($paymentId);
113
        
114
        if (!$this->plugin->isKlarnaKcoPaymentActive($user) && $this->plugin->isKlarnaUser()) {
115
            $session->offsetUnset('sUserId');
116
            $session->offsetSet('sRegisterFinished', false);
117
            $this->plugin->removeKlarnaUsers();
118
        }
119
120
        $this->forward('index');
121
    }
122
123
   /**
124
     * @param Klarna_Checkout_Order $order
125
     */
126
    public function createAccount($order = null, $checkLoginState=true)
127
    {
128
        $this->plugin->klarnaLog('Entering Shopware_Controllers_Frontend_PaymentKlarna::createAccount', 3);
129
        $module = Shopware()->Modules()->Admin();
130
        $session = Shopware()->Session();
131
132
        $version = Shopware()->Config()->version;
133
        if ($version == '___VERSION___' || version_compare($version, '4.1.0', '>=')) {
134
            $encoder = Shopware()->PasswordEncoder()->getDefaultPasswordEncoderName();
135
        }
136
        
137
        $data = array();
138
139
        if ($order !== null && !empty($order['billing_address']['email'])) {
140
            $data['auth']['email'] = $order['billing_address']['email'];
141
            $data['auth']['password'] = $order['reference'];
142
        } else {
143
            $sessionId = Shopware()->SessionID();
144
            // email is only varchar(70) so we cut the sessionid
145
            //$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...
146
            $data['auth']['email'] = substr($sessionId, 0,49) . '@klarna.com';
147
            $data['auth']['password'] = $sessionId;
148
        }
149
        $data['auth']['accountmode'] = '1';
150
151
        $phone = $order['billing_address']['phone'];
152
        $data['billing']['phone'] = !empty($phone) ? $phone : ' ';
153
        $data['phone'] = !empty($phone) ? $phone : ' ';
154
        if (!empty($order['customer']['date_of_birth'])) {
155
            list($data['billing']['birthyear'], $data['billing']['birthmonth'], $data['billing']['birthday']) = explode(
156
                '-',
157
                $order['customer']['date_of_birth']
158
            );
159
        }
160
161
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->order:",4, $order);
162
        
163
        foreach (array('billing', 'shipping') as $type) {
164
            if (isset($order[$type . '_address'])) {
165
                $orderAddress = $order[$type . '_address'];
166
                if (isset($orderAddress['title'])) {
167
                    $data[$type]['salutation'] = $orderAddress['title'] == 'Frau' ? 'ms' : 'mr';
168
                } else {
169
                    $data[$type]['salutation'] = 'mr';
170
                }
171
                $data[$type]['firstname'] = $orderAddress['given_name'];
172
                $data[$type]['lastname'] = $orderAddress['family_name'];
173
                if (isset($orderAddress['street_name']) && $orderAddress['street_number']) {
174
                    if (version_compare(Shopware::VERSION, '5.0.0', '>=')) {
175
                        $data[$type]['street'] = $orderAddress['street_name'] . ' ' . $orderAddress['street_number'];
176 View Code Duplication
                    } else {
1 ignored issue
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...
177
                        $data[$type]['street'] = $orderAddress['street_name'];
178
                        $data[$type]['streetnumber'] = $orderAddress['street_number'];
179
                    }
180
                } else {
181
                    $data[$type]['street'] = $orderAddress['street_address'];
182
                    $data[$type]['streetnumber'] = ' ';
183
                }
184
                $data[$type]['zipcode'] = $orderAddress['postal_code'];
185
                $data[$type]['city'] = $orderAddress['city'];
186
                if (!empty($orderAddress['care_of'])) {
187
                    if ($orderAddress['street_name'] == 'Packstation') {
188
                        $data[$type]['postnumber'] = $orderAddress['care_of'];
189
                        $data[$type]['swagDhlPostnumber'] = $data[$type]['postnumber'];
190
                    } else {
191
                        $data[$type]['company'] = $orderAddress['care_of'];
192
                    }
193
                }
194
            } else {
195
                $data[$type]['salutation'] = 'mr';
196
                $data[$type]['firstname'] = 'Klarna Firstname';
197
                $data[$type]['lastname'] = 'Klarna Checkout';
198
                $data[$type]['street'] = 'Klarna Street';
199
                $data[$type]['streetnumber'] = ' ';
200
                $data[$type]['zipcode'] = '00000';
201
                $data[$type]['city'] = 'Klarna City ';
202
                $data[$type]['birthday'] = '0000-00-00';
203
                $data[$type]['phone'] = '00000000';
204
            }
205
            if (!isset($data[$type]['company'])) {
206
                $data[$type]['company'] = '';
207
            }
208
            $data[$type]['department'] = '';
209
210
            if (!empty($order[$type . '_address']['country'])) {
211
                $sql = 'SELECT id FROM s_core_countries WHERE countryiso=?';
212
                $countryId = Shopware()->Db()->fetchOne($sql, array($order[$type . '_address']['country']));
213
            } else {
214
                $countryId = $session['sCountry'];
215
            }
216
            // make sure country is set in case of lost sessions defualt to germany
217
            if (empty($countryId)){
218
                $countryId = 2;
219
            }            
220
221
            $data[$type]['country'] = $countryId;
222
        }
223
224
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->data AFTER ADDRESSES:",4,$data);
225
        $sql = 'SELECT id FROM s_core_paymentmeans WHERE name=?';
226
        $paymentId = Shopware()->Db()->fetchOne($sql, array('klarna_checkout'));
227
228
        if ($order !== null && !empty($order['billing_address']['email'])) {
229
            $shop = $this->get('shop');
230
            $shop = $shop->getMain() ?: $shop;
231
            $sql = 'SELECT id, email, `password` FROM `s_user` WHERE `email` LIKE ? AND `active` = 1 ';
232
            if ($shop->getCustomerScope()) {
233
                $sql .= "AND `subshopID` = {$shop->getId()} ";
234
            }
235
            $sql .= 'ORDER BY `accountmode`';
236
            $user = Shopware()->Db()->fetchRow($sql, array($data['auth']['email']));
237
            // First try login 
238
            if (!empty($user)) {
239
                $session->offsetSet('sUserMail', $user['email']);
240
                $session->offsetSet('sUserPassword', $user['password']);
241
                $session->offsetSet('sUserId', $user['id']);
242
            } else {
243
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->user Not Found in DB SQL was:" .$sql,1);                
244
            }
245
        }
246
247
        if ($checkLoginState) {
248
            // Check login status
249
            if (!empty($session->sUserId)) {
250
                if ($order !== null) {
251
                    $module->sSYSTEM->_POST = $data['shipping'];
252 View Code Duplication
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
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...
253
                        $userId = $session->offsetGet('sUserId');
254
                        $this->updateShipping($userId, $data['shipping']);
255
                    } else {
256
                        $module->sUpdateShipping();
257
                    }
258
                    $module->sSYSTEM->_POST = $data['billing'];
259 View Code Duplication
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {                
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...
260
                         $userId = $session->offsetGet('sUserId');
261
                         $this->updateBilling($userId, $data['billing']);
262
                    } else{
263
                        $module->sUpdateBilling();
264
                    }
265
                    unset($data['auth']['password']);
266
                    $module->sSYSTEM->_POST = $data['auth'];
267
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
268
                        $userId = $session->offsetGet('sUserId');
269
                        $this->updateCustomer($data, $userId);
270
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->updateCustomer:",3, $data);                                                
271
                    } else{
272
                        $module->sUpdateAccount();
273
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->updateAccount:",3, $this->front->Request()->getPost());                                                                        
274
                    }
275
                } else {
276
                    /** @var Enlight_Controller_Front $front */
277
                    $front = $this->get('front');
278
                    $front->Request()->setPost(array());
279
                    $module->sSYSTEM->_POST = array('country' => $data['shipping']['country']);
280
                    $shippingId = $this->get('db')->fetchOne(
281
                        'SELECT id FROM s_user_shippingaddress WHERE userID = ?',
282
                        array($session->offsetGet('sUserId'))
283
                    );
284 View Code Duplication
                    if (!empty($shippingId)) {
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...
285
                        if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
286
                            $userId = $session->offsetGet('sUserId');
287
                            $this->updateShipping($userId, $data['shipping']);
288
                        } else {
289
                            $module->sUpdateShipping();
290
                        }
291
                    } else {
292
                        $module->sUpdateBilling();
293
                    }
294
                }
295
                $module->sSYSTEM->_POST = array('sPayment' => $paymentId);
296
                $module->sUpdatePayment();
297
            } else {
298
                $data['payment']['object'] = $module->sGetPaymentMeanById($paymentId);
299
                if (isset($encoder)) {
300
                    $data["auth"]["encoderName"] = $encoder;
301
                    $data["auth"]["password"] = Shopware()->PasswordEncoder()->encodePassword($data["auth"]["password"], $encoder);
302
                } else {
303
                    $data['auth']['password'] = md5($data['auth']['password']);
304
                }
305
                $session->sRegisterFinished = false;
306
                if (version_compare(Shopware::VERSION, '4.3.0', '>=') && version_compare(Shopware::VERSION, '5.2.0', '<')) {
307
                    $session->sRegister = $data;
308
                } elseif (version_compare(Shopware::VERSION, '4.3.0', '<')) {
309
                    $session->sRegister = new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS);
310
                }
311
                try {
312
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
313
                        $newdata = $this->saveUser($data);
314
                        $module->sSYSTEM->_POST = $newdata['auth'];
315
                        $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...
316
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser:",3, $newdata);                        
317
                        // $this->returnAction();
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...
318
                    } else {
319
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser->Register:",3, $session->sRegister);                         
320
                        $module->sSaveRegister();
321
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser->RegisterFinished:",3, $session->offsetGet('sRegisterFinished')); 
322
                    }
323
                    
324
                } catch (\Exception $ex) { /* do nothing */
325
                    $this->klarnaLog("ERROR while creating User. Exception information:".$ex->getMessage(),1);
326
                    
327
                }
328
            }
329
            
330
        }
331
        
332
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->data END OF METHOD:",4, $data);
333
    }
334
    
335
    /**
336
     * Saves a new user to the system.
337
     *
338
     * @param array $data
339
     */
340
    private function saveUser($data)
341
    {
342
343
        $builder = Shopware()->Models()->createQueryBuilder();
0 ignored issues
show
Unused Code introduced by
$builder 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...
344
        $plain = array_merge($data['auth'], $data['shipping']);
345
346
        //Create forms and validate the input
347
        $customer = new Shopware\Models\Customer\Customer();
348
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\PersonalFormType', $customer);
349
        $form->submit($plain);
350
351
        $address = new Shopware\Models\Customer\Address();
352
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\AddressFormType', $address);
353
        $form->submit($plain);
354
355
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface $context */
356
        $context = $this->get('shopware_storefront.context_service')->getShopContext();
357
358
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\Shop $shop */
359
        $shop = $context->getShop();
360
361
        /** @var Shopware\Bundle\AccountBundle\Service\RegisterServiceInterface $registerService */
362
        $registerService = $this->get('shopware_account.register_service');
363
        $registerService->register($shop, $customer, $address, $address);
364
365
        // get updated password; it is md5 randomized after register
366
        $getUser = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
367
		array('email' =>  $data['auth']['email'])
368
		);
369
370
       $data['auth']['password']= $getUser->getPassword();
371
       $data['auth']['passwordMD5']= $getUser->getPassword();
372
       $data['auth']['encoderName'] = 'md5';
373
        return $data;
374
    }
375
376
377
    /**
378
     * Endpoint for changing the main profile data
379
     */
380
    public function updateCustomer($data, $userId)
381
    {
382
        $data['birthdate'] = $data['billing']['birthyear'].'-'.$data['billing']['birthmonth'].'-'.$data['billing']['birthday'];
383
        $data['birthday'] = $data['birthdate'];    
384
        $data['email'] = $data['auth']['email'];
385
        $data['firstname'] = $data['billing']['firstname'];
386
        $data['lastname'] = $data['billing']['lastname'];
387
        unset ($data['shipping']);
388
        unset ($data['billing']);        
389
390
        $customer = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
391
		array('id' =>  $userId)
392
		);
393
        $customer->fromArray($data);
394
        Shopware()->Container()->get('shopware_account.customer_service')->update($customer);
395
    }
396
397
398
     /**
399
     * Updates the shipping address
400
     *
401
     * @param int $userId
402
     * @param array $shippingData
403
     */
404
    private function updateShipping($userId, $shippingData)
405
    {
406
        /** @var \Shopware\Components\Model\ModelManager $em */
407
        $em = $this->get('models');
408
409
        /** @var \Shopware\Models\Customer\Customer $customer */
410
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(array('id' => $userId));
411
412
        /** @var \Shopware\Models\Customer\Address $address */
413
        $addressold = $customer->getDefaultShippingAddress();
414
        $address = new \Shopware\Models\Customer\Address();
415
        
416
         /** @var \Shopware\Models\Country\Country $country */
417
        $country = $addressold->getCountry();
418
        $shippingData['country'] = $country;
419
        if ($shippingData['phone'] === null) {
420
            $shippingData['phone'] = ' ';
421
        }
422
        $address->fromArray($shippingData);
423
        try {
424
            $addressService = $this->get('shopware_account.address_service');
425
            $addressService->create($address, $customer);
426
            $addressService->setDefaultShippingAddress($address);
427
        } catch (Exception $ex) {
428
            $this->klarnaLog("ERROR while creating address via address service. Exception information:".$ex->getMessage(),1);
429
        }
430
        
431
    }
432
433
    /**
434
     * Updates the billing address
435
     *
436
     * @param int $userId
437
     * @param array $billingData
438
     */
439
    private function updateBilling($userId, $billingData)
440
    {
441
        /** @var \Shopware\Components\Model\ModelManager $em */
442
        $em = $this->get('models');
443
444
        /** @var \Shopware\Models\Customer\Customer $customer */
445
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(array('id' => $userId));
446
447
        /** @var \Shopware\Models\Customer\Address $address */
448
        $address = $customer->getDefaultBillingAddress();
449
        
450
         /** @var \Shopware\Models\Country\Country $country */
451
        $country = $address->getCountry();
452
        $billingData['country'] = $country;
453
        $address->fromArray($billingData);
454
455
        $this->get('shopware_account.address_service')->update($address);
456
    }
457
458
459
    /**
460
     * Needed to reset the session when the user logs in
461
     */
462
    public function loginAction()
463
    {
464
        Shopware()->Session()->offsetSet('KlarnaOrder', null);
465
        $this->redirect(array('controller' => 'payment_klarna', 'action' => 'express'));
466
    }
467
468
    /**
469
     * Return action method
470
     *
471
     * Reads the transactionResult and represents it for the customer.
472
     */
473
    public function returnAction()
474
    {
475
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction",3);
476
        if ($this->getPaymentShortName() != 'klarna_checkout') {
477
            $this->forward('index');
478
            return;
479
        }
480
        $transactionId = $this->Request()->getParam('transactionId');
481
        
482
        $connector = $this->plugin->getConnector();
483
484
        $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...
485
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->transactionId:\n".$transactionId,3);
486
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->order:",4, $order);
487
        $orderNumber = '';
488
        
489
        try {
490
            $order->fetch();
491
492
            $this->createAccount($order);
493
            $this->plugin->updateOrderVariables();
494
495
            if ($order['status'] == 'checkout_complete') {
496
                $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: checkout_complete. Save oder if session values match.",3);
497
                if (Shopware()->Session()->offsetGet('KlarnaTransactionId') == null){
498
                    $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: Session matches. Order will be saved",3);
499
                    Shopware()->Session()->offsetSet('KlarnaTransactionId', $transactionId );
500
                    $orderNumber = $this->saveOrder(
501
                        $order['reservation'],
502
                        $order['reference']
503
                    );
504
                    Shopware()->Session()->offsetSet('KlarnaTransactionId', null );                
505
                }
506
507
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::returnAction: checkout_complete. Check if Order was persisted in DB.",3);    
508
509
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::returnAction: checkout_complete. Searching for Order:",3);
510
                $this->checkKlarnaOrderExistsByReservation($order['reservation']);
511
                $this->checkKlarnaOrderExistsByReference($order['reference']);
512
                $this->checkKlarnaOrderExistsBySession(Shopware()->Session()->sUserId);
513
                $this->checkKlarnaOrderDetailsBySession(Shopware()->Session()->sUserId);
514
            }
515
516
            if (empty($orderNumber) && !empty($order['merchant_reference']['orderid1'])) {
517
                $orderNumber = $order['merchant_reference']['orderid1'];
518
            }
519
            $update = array();
520
            $update['merchant_reference'] = array(
521
                'orderid1' => (string) $orderNumber,
522
                'orderid2' => (string) $order['reference']
523
            );
524
            $order->update($update);   
525
           
526
            // Saves postnumber for dhl packstation
527
            if (!empty($orderNumber)
528
                && !empty($order['shipping_address']['care_of'])
529
                && $order['shipping_address']['street_name'] == 'Packstation'
530
                && $this->config->get('postnumberField')
531
            ) {
532
                $field = $this->config->get('postnumberField');
533
                $value = $order['shipping_address']['care_of'];
534
                $this->saveOrderAttribute($orderNumber, $field, $value);
535
            }
536
537
            if ($order['status'] == 'created' || $order['status'] == 'checkout_complete') {
538
                $this->saveOrderAttribute($orderNumber, 'swag_klarna_status', 'created');
539
                $this->savePaymentStatus(
540
                                $order['reservation'],
541
                                $order['reference'],
542
                                $this->config->get('statusId')
543
                            );                
544
                $this->redirect(array(
545
                    'controller' => 'checkout',
546
                    'action' => 'finish',
547
                    'sUniqueID' => $order['reference']
548
                ));
549
            } else {
550
                $this->redirect(array('controller' => 'checkout', 'action' => 'confirm'));
551
            }
552
        } catch (Exception $e) {
553
            Shopware()->Plugins()->Controller()->ViewRenderer()->setNoRender();
554
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::returnAction: Catch. Searching for Order:",3);   
555
            $this->checkKlarnaOrderExistsByReservation($order['reservation']);
556
            $this->checkKlarnaOrderExistsByReference($order['reference']);
557
            $this->checkKlarnaOrderExistsBySession(Shopware()->Session()->sUserId); 
558
            $this->checkKlarnaOrderDetailsBySession(Shopware()->Session()->sUserId); 
559
            echo "Entschuldigung, Ein Verbindungsfehler ist aufgetreten, bitte aktualisieren Sie die Seite";
560
        }            
561
    }
562
    
563
    /**
564
     * Method checks if certain klarna order exists or not
565
     * 
566
     * @param string $sessionID
567
     * @return bool
568
     */
569 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...
570
        $sql = '
571
            SELECT * FROM s_order
572
            WHERE userID=?
573
        ';
574
        
575
        $order = Shopware()->Db()->fetchAll($sql, array(
576
                $sessionID
577
        ));
578
        
579
        $orderExists = (empty($order)) ? false : true;
580
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession:",3);   
581
        if ($orderExists){
582
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession: Order Found: ",3, $order);   
583
        }
584
        return $orderExists;
585
    }    
586
    
587
    /**
588
     * Method checks if certain klarna order exists or not
589
     * 
590
     * @param string $transactionId
0 ignored issues
show
Bug introduced by
There is no parameter named $transactionId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
591
     * @param string $paymentUniqueId
592
     * @return bool
593
     */
594 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...
595
        $sql = '
596
            SELECT * FROM s_order
597
            WHERE temporaryID=?
598
        ';
599
        
600
        $order = Shopware()->Db()->fetchAll($sql, array(
601
                $paymentUniqueId
602
        ));
603
        
604
        $orderExists = (empty($order)) ? false : true;
605
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference:",3);   
606
        if ($orderExists){
607
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference: Order Found: ",3, $order);   
608
        }
609
        return $orderExists;
610
    }
611
    
612
    /**
613
     * Method checks if certain klarna order exists or not
614
     * 
615
     * @param string $transactionId
616
     * @param string $paymentUniqueId
0 ignored issues
show
Bug introduced by
There is no parameter named $paymentUniqueId. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
617
     * @return bool
618
     */
619 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...
620
        $sql = '
621
            SELECT * FROM s_order
622
            WHERE transactionID=?
623
        ';
624
        
625
        $order = Shopware()->Db()->fetchAll($sql, array(
626
                $transactionId
627
        ));
628
        
629
        $orderExists = (empty($order)) ? false : true;
630
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation:",3);   
631
        if ($orderExists){
632
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation: Order Found: ",3, $order);   
633
        }
634
        return $orderExists;
635
    }    
636
    
637
    /**
638
     * Method checks if certain klarna order exists or not
639
     * 
640
     * @param string $transactionId
641
     * @param string $paymentUniqueId
642
     * @param string $userId
643
     * @return bool
644
     */
645
    protected function checkKlarnaOrderExists($transactionId, $paymentUniqueId, $userId) {
646
        $sql = '
647
            SELECT ordernumber FROM s_order
648
            WHERE transactionID=? AND temporaryID=?
649
            AND status!=-1 AND userID=?
650
        ';
651
        
652
        $orderNumber = Shopware()->Db()->fetchOne($sql, array(
653
                $transactionId,
654
                $paymentUniqueId,
655
                $userId
656
        ));
657
        
658
        $orderExists = (empty($orderNumber)) ? false : true;
659
        
660
        return $orderExists;
661
    }
662
    
663
    /**
664
     * Method checks if certain klarna order exists or not
665
     * 
666
     * @param string $sessionID
667
     * @return bool
668
     */
669 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...
670
        $sql = '
671
            SELECT * FROM s_order
672
            LEFT JOIN s_order_details ON s_order.id = s_order_details.orderID
673
            WHERE userID=?
674
        ';
675
        
676
        $orderDetails = Shopware()->Db()->fetchAll($sql, array(
677
                $sessionID
678
        ));
679
        
680
        $orderExists = (empty($orderDetails)) ? false : true;
681
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession:",3);   
682
        if ($orderExists){
683
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession: OrderDetails Found: ",3, $orderDetails);
684
        }
685
        return $orderExists;
686
    }
687
    
688
    /**
689
     * Method checks if certain klarna order exists or not
690
     * 
691
     * @param string $paymentUniqueId
692
     * @return string
693
     */
694
    protected function getUserIdByReference($paymentUniqueId) {
695
        $sql = '
696
            SELECT userID FROM s_order
697
            WHERE temporaryID=?
698
        ';
699
        
700
        $userId = Shopware()->Db()->fetchOne($sql, array(
701
                $paymentUniqueId
702
        ));
703
704
        return $userId;
705
    }    
706
    
707
    /**
708
     *
709
     *
710
     * @param string $transactionId
711
     * @param string $paymentUniqueId
712
     * @param string $userId
713
     * @return string $orderNumber
714
     */
715 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...
716
        $sql = '
717
            SELECT ordernumber FROM s_order
718
            WHERE transactionID=? AND temporaryID=?
719
            AND status!=-1 AND userID=?
720
        ';
721
722
        $orderNumber = Shopware()->Db()->fetchOne($sql, array(
723
            $transactionId,
724
            $paymentUniqueId,
725
            $userId
726
        ));
727
728
        return $orderNumber;
729
    }
730
731
    /**
732
     *
733
     *
734
     * @param string $transactionId
735
     * @param string $paymentUniqueId
736
     * @param string $userId
737
     * @return string $orderId
738
     */
739 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...
740
        $sql = '
741
            SELECT id FROM s_order
742
            WHERE transactionID=? AND temporaryID=?
743
            AND status!=-1 AND userID=?
744
        ';
745
746
        $orderId = Shopware()->Db()->fetchOne($sql, array(
747
            $transactionId,
748
            $paymentUniqueId,
749
            $userId
750
        ));
751
752
        return $orderId;
753
    }
754
755
756
    /**
757
     * Notify action method
758
     */
759
    public function pushAction()
760
    {
761
        $transactionId = $this->Request()->getParam('transactionId');
762
       
763
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction->transactionId:\n".$transactionId,3);
764
        $connector = $this->plugin->getConnector();
765
        $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...
766
        $order->fetch();
767
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction->order:",4, $order);
768
        
769
        $userId = $this->getUserIdByReference($order['reference']);
770
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction->UserID: " .$userId ,3);
771
        // before continuing its mandatory to check if order has been persisted
772
        $orderExists = $this->checkKlarnaOrderExists($order['reservation'], $order['reference'], $userId);
773
        if (!$orderExists) {
774
            /**
775
             * @todo: Adding mechanism so that cancel signal will be send to klarna, if push notifications are over the limit of about 2 calls
776
             */
777
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction: checkout_complete. Order was not persisted in DB, UserId is" .$userId ,1);    
778
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction: checkout_complete. Searching for Order:",1);   
779
                $this->checkKlarnaOrderExistsByReservation($order['reservation']);
780
                $this->checkKlarnaOrderExistsByReference($order['reference']);
781
                $this->checkKlarnaOrderExistsBySession($userId);  
782
                $this->checkKlarnaOrderDetailsBySession($userId); 
783
                return;
784
        }
785
        
786
        $orderNumber = $this->getKlarnaOrderNumber($order['reservation'], $order['reference'], $userId);
787
        $orderId = $this->getKlarnaOrderId($order['reservation'], $order['reference'], $userId);
788
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction: Found Order was found in DB... Sending Update to Klarna: " .$orderNumber,1);
789
790
        // Check if Order Username ist false (Klarna Firstname)
791
792
        $swUser = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
793
            array('id' =>  $userId )
794
        );
795
796
        $firstName = $swUser->getBilling()->getFirstname();
797
       if ($firstName === 'Klarna Firstname') {
798
           $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction: Found Order with Klarna Firstname, updating from Klarna data: " .$orderNumber,1);
799
           $data['billing']['salutation'] = $order['billing_address']['title'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
800
           $data['billing']['firstname'] = $order['billing_address']['given_name'];
801
           $data['billing']['lastname'] = $order['billing_address']['family_name'];
802
           $data['billing']['street'] = $order['billing_address']['street_name']." ". $order['billing_address']['street_number'];           
803
           $data['billing']['zipcode'] = $order['billing_address']['postal_code'];
804
           $data['billing']['city'] = $order['billing_address']['city'];
805
           $data['billing']['birthday'] = $order['customer']['date_of_birth'];
806
           $data['billing']['phone'] = $order['billing_address']['phone'];
807
808
           $data['shipping']['salutation'] = $order['shipping_address']['title'];
809
           $data['shipping']['firstname'] = $order['shipping_address']['given_name'];
810
           $data['shipping']['lastname'] = $order['shipping_address']['family_name'];
811
           $data['shipping']['street'] = $order['shipping_address']['street_name']." ". $order['shipping_address']['street_number'];
812
           $data['shipping']['zipcode'] = $order['shipping_address']['postal_code'];
813
           $data['shipping']['city'] = $order['shipping_address']['city'];
814
           $data['shipping']['birthday'] = $order['customer']['date_of_birth'];
815
           $data['shipping']['phone'] = $order['shipping_address']['phone'];
816
           // Update Customer
817
           if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
818
                unset ($data['billing']['birthday']);
819
                unset ($data['shipping']['birthday']);
820
                unset ($data['shipping']['phone']);                
821
               
822
                $customer = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
823
                    array('id' =>  $userId)
824
                    );
825
                $customer->fromArray($data);
826
                Shopware()->Container()->get('shopware_account.customer_service')->update($customer);
827
                
828
               $this->updateShipping($userId, $data['shipping']);
829
               $this->updateBilling($userId, $data['billing']);
830
               
831
               // Update Order Addresses
832
833
               $orderShippingID = Shopware()->Db()->fetchOne(
834
                   'SELECT id FROM s_order_shippingaddress WHERE userID = ? AND orderID = ?',
835
                   array($userId, $orderId)
836
               );
837
               $where = array('id='.(int) $orderShippingID);
838
               Shopware()->Db()->update('s_order_shippingaddress',  $data['shipping'], $where);
839
840
               $orderBillingID = Shopware()->Db()->fetchOne(
841
                   'SELECT id FROM s_order_billingaddress WHERE userID = ? AND orderID = ?',
842
                   array($userId, $orderId)
843
               );
844
               $where = array('id='.(int) $orderBillingID);
845
               Shopware()->Db()->update('s_order_billingaddress',  $data['billing'], $where);
846
               
847
           } else{
848
849
               // Append streetnumber to street and unset field for sw 5.1
850
               // unset birthday too
851
852
               // Update User Addresses
853
               unset ($data['shipping']['birthday']);
854
               unset ($data['shipping']['phone']);
855
856
               $shippingID = Shopware()->Db()->fetchOne(
857
                   'SELECT id FROM s_user_shippingaddress WHERE userID = ?',
858
                   array($userId)
859
               );
860
               $where = array('id='.(int) $shippingID);
861
               Shopware()->Db()->update('s_user_shippingaddress',  $data['shipping'], $where);
862
863
               $billingID = Shopware()->Db()->fetchOne(
864
                   'SELECT id FROM s_user_billingaddress WHERE userID = ?',
865
                   array($userId)
866
               );
867
               $where = array('id='.(int) $billingID);
868
               Shopware()->Db()->update('s_user_billingaddress',  $data['billing'], $where);
869
870
871
               // Update Order Addresses
872
873
               $orderShippingID = Shopware()->Db()->fetchOne(
874
                   'SELECT id FROM s_order_shippingaddress WHERE userID = ? AND orderID = ?',
875
                   array($userId, $orderId)
876
               );
877
               $where = array('id='.(int) $orderShippingID);
878
               Shopware()->Db()->update('s_order_shippingaddress',  $data['shipping'], $where);
879
880
               $orderBillingID = Shopware()->Db()->fetchOne(
881
                   'SELECT id FROM s_order_billingaddress WHERE userID = ? AND orderID = ?',
882
                   array($userId, $orderId)
883
               );
884
               $where = array('id='.(int) $orderBillingID);
885
               Shopware()->Db()->update('s_order_billingaddress',  $data['billing'], $where);
886
887
           }
888
       }
889
890
        $update = array();
891
        $update['status'] = 'created';
892
        $update['merchant_reference'] = array(
893
            'orderid1' => (string) $orderNumber,
894
            'orderid2' => (string) $order['reference']
895
        );
896
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction: Update Klarna ",1, $update);
897
        $order->update($update);
898
        $this->savePaymentStatus(
899
            $order['reservation'],
900
            $order['reference'],
901
            $this->config->get('statusId')
902
        );
903
    }
904
905
    private function saveOrderAttribute($orderNumber, $field, $value)
906
    {
907
        try {
908
            $sql = "
909
                INSERT INTO s_order_attributes (orderID, `$field`)
910
                SELECT id, ? FROM s_order WHERE ordernumber = ?
911
                ON DUPLICATE KEY UPDATE `$field` = VALUES(`$field`)
912
            ";
913
            $this->get('db')->query($sql, array(
914
                $value,
915
                $orderNumber
916
            ));
917
        } catch (Exception $e) {
918
            $this->plugin->klarnaLog("PROBLEM SAVING ORDER ATTRIBUTES AFTER KLARNA PUSH!:\n".$e->getMessage(),1);
919
        }
920
    }
921
922
    /**
923
     * Save register form so we can use it if user change between klarna and register tab
924
     */
925
    public function saveFormDataAction()
926
    {
927
        $form = $this->Request()->getPost();
928
929
        //unset password from passed post
930
        unset($form['register']['personal']['password']);
931
932
        if (!empty($form)) {
933
            Shopware()->Session()->klarnaSavedRegister = $form;
934
        }
935
    }
936
937
    /**
938
     * Helper method to redirect the request to the proper page to set the payment into the customer account
939
     */
940
    public function setPaymentAction()
941
    {
942
        if ($this->Request()->isPost()) {
943
            $values = $this->Request()->getPost('register');
944
            $payment = $values['payment'];
945
        } else {
946
            $payment = $this->Request()->getParam('paymentId');
947
        }
948
949
        if (empty($payment)) {
950
            return;
951
        }
952
953
        $user = Shopware()->Modules()->Admin()->sGetUserData();
954
        if (empty($user) || $user['billingaddress']['lastname'] == 'Klarna Checkout') {
955
            $session = Shopware()->Session();
956
            $session->offsetSet('sPaymentID', $payment);
957
            $session->offsetUnset('sUserId');
958
            $session->offsetSet('sRegisterFinished', false);
959
960
            $this->redirect(
961
                array(
962
                    'controller' => 'register',
963
                    'action' => 'index',
964
                    'sTarget' => 'checkout',
965
                    'sTargetAction' => 'confirm'
966
                )
967
            );
968
        } else {
969
            $this->savePayment($payment);
970
            $this->redirect(
971
                array(
972
                    'controller' => 'checkout',
973
                    'action' => 'confirm'
974
                )
975
            );
976
        }
977
    }
978
979
    /**
980
     * This action is called when the user is not logged in and tries to change the payment from klarna to another payment.
981
     * Only used in responsive theme.
982
     */
983
    public function otherPaymentAction()
984
    {
985
        $userData = Shopware()->Modules()->Admin()->sGetUserData();
986
        $session = Shopware()->Session();
987
988
        // When the user is a valid user and accidentally calls this action, we don't want to reset his session
989
        if ($userData['billingaddress']['lastname'] == 'Klarna Checkout') {
990
            $session->offsetUnset('sUserId');
991
992
            //Remove all temporary klarna-users older than 24 hours
993
            Shopware()->Plugins()->Frontend()->SwagPaymentKlarna()->removeKlarnaUsers();
994
            $session->offsetSet('sRegisterFinished', false);
995
        }
996
        
997
            // reset country
998
            $session['sCountry'] = $userData['additional']['country']['id'];
999
            unset($session['sChangedCountry']);
1000
1001
        //Register-controller redirects to checkout by default when the user is logged in already.
1002
        $this->redirect(array(
1003
            'controller' => 'register',
1004
            'klarnaRedirect' => 1,
1005
            'sTarget' => 'checkout',
1006
            'sTargetAction' => 'shippingPayment'
1007
        ));
1008
    }
1009
1010
    /**
1011
     * Helper method to set the selected payment-method into the session to change it in the customer-account after logging in
1012
     *
1013
     * @param $paymentId
1014
     * @throws Enlight_Exception
1015
     */
1016
    private function savePayment($paymentId)
1017
    {
1018
        $admin = Shopware()->Modules()->Admin();
1019
        $admin->sSYSTEM->_POST['sPayment'] = $paymentId;
1020
        $validation = $admin->sValidateStep3();
1021
1022
        if (!empty($validation['checkPayment']['sErrorMessages']) || empty($validation['sProcessed'])) {
1023
            $this->View()->assign('sErrorFlag', $validation['checkPayment']['sErrorFlag']);
1024
            $this->View()->assign('sErrorMessages', $validation['checkPayment']['sErrorMessages']);
1025
        } else {
1026
            $previousPayment = $admin->sGetUserData();
1027
            $previousPayment = $previousPayment['additional']['user']['paymentID'];
1028
1029
            $previousPayment = $admin->sGetPaymentMeanById($previousPayment);
1030
            if ($previousPayment['paymentTable']) {
1031
                $deleteSQL = 'DELETE FROM '.$previousPayment['paymentTable'].' WHERE userID=?';
1032
                Shopware()->Db()->query($deleteSQL, array(Shopware()->Session()->offsetGet('sUserId')));
1033
            }
1034
1035
            $admin->sUpdatePayment();
1036
1037
            if ($validation['sPaymentObject'] instanceof \ShopwarePlugin\PaymentMethods\Components\BasePaymentMethod) {
0 ignored issues
show
Bug introduced by
The class ShopwarePlugin\PaymentMe...nents\BasePaymentMethod does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
1038
                $validation['sPaymentObject']->savePaymentData(Shopware()->Session()->offsetGet('sUserId'), $this->Request());
1039
            }
1040
        }
1041
    }
1042
    
1043
    protected function isUserLoggedIn($session)
1044
    {        
1045
         return (isset($session->sUserId) && !empty($session->sUserId));
1046
    }    
1047
}
1048