Passed
Push — master ( 54a344...83c53d )
by Mario
03:09
created

createAccount()   F

Complexity

Conditions 44
Paths > 20000

Size

Total Lines 208
Code Lines 154

Duplication

Lines 26
Ratio 12.5 %

Importance

Changes 0
Metric Value
cc 44
dl 26
loc 208
rs 2
c 0
b 0
f 0
eloc 154
nc 4665600
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * Klarna payment controller
5
 */
6
class Shopware_Controllers_Frontend_PaymentKlarna extends Shopware_Controllers_Frontend_Payment
7
{
8
    /**
9
     * @var Shopware_Plugins_Frontend_SwagPaymentKlarna_Bootstrap
10
     */
11
    private $plugin;
12
13
    /**
14
     * @var Enlight_Config
15
     */
16
    private $config;
17
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function preDispatch()
22
    {
23
        $this->plugin = $this->get('plugins')->Frontend()->SwagPaymentKlarna();
24
        $this->config = $this->plugin->Config();
25
        if (in_array($this->Request()->getActionName(), array('push', 'saveFormData'))) {
26
            $this->Front()->Plugins()->ViewRenderer()->setNoRender();
27
        }
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 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...
34
    {
35
        if (version_compare(Shopware::VERSION, '4.2.0', '<') && Shopware::VERSION != '___VERSION___') {
36
            if ($name == 'pluginlogger') {
37
                $name = 'log';
38
            }
39
            $name = ucfirst($name);
40
            return Shopware()->Bootstrap()->getResource($name);
41
        }
42
        return parent::get($name);
43
    }
44
    
45
    /**
46
     * Index action method.
47
     *
48
     * Forwards to correct the action.
49
     */
50
    public function indexAction()
51
    {
52
        $this->redirect(array('controller' => 'checkout', 'action' => 'confirm'));
53
    }
54
55
    /**
56
     * Express payment action method.
57
     */
58
    public function expressAction()
59
    {
60
        $session = Shopware()->Session();
61
        
62
        if (!empty($session->PaypalResponse)){
63
            $this->plugin->klarnaLog("Paypal Payment in Progress detected Redirecting To Index Page", 3);
64
            $this->redirect(
65
                array(
66
                    'controller' => 'index',
67
                    'action' => 'index'
68
                )
69
            );
70
            return;
71
        }        
72
        
73
        if ($this->Request()->getPost('sCountry')) {
74
            $session['sCountry'] = (int)$this->Request()->getPost('sCountry');
75
            $session["sState"] = 0;
76
            $session["sArea"] = Shopware()->Db()->fetchOne("
77
                SELECT areaID FROM s_core_countries WHERE id = ?
78
            ", array($session['sCountry']));
79
            unset($session->KlarnaOrder);
80
            $session['sChangedCountry'] = (int)$this->Request()->getPost('sCountry');
81
        }
82
        
83
        if (!$this->isUserLoggedIn($session)){
84
	        $this->createAccount();
85
	}
86
        
87
        $user = Shopware()->Modules()->Admin()->sGetUserData();
88
        if ($this->Request()->getPost('sCountry')) {
89
          $session['sCountry'] = $this->Request()->getPost('sCountry'); 
90
          $session['sChangedCountry'] = $this->Request()->getPost('sCountry'); 
91
        }
92
93
        // Switch Paymentmean to Klarna Checkout
94
        $sql = 'SELECT id FROM s_core_paymentmeans WHERE name=?';
95
        $paymentId = Shopware()->Db()->fetchOne($sql, array('klarna_checkout'));
96
        $this->savePayment($paymentId);
97
        
98
        if (!$this->plugin->isKlarnaKcoPaymentActive($user) && $this->plugin->isKlarnaUser()) {
99
            $session->offsetUnset('sUserId');
100
            $session->offsetSet('sRegisterFinished', false);
101
            $this->plugin->removeKlarnaUsers();
102
        }
103
104
        $this->forward('index');
105
    }
106
107
   /**
108
     * @param Klarna_Checkout_Order $order
109
     */
110
    public function createAccount($order = null, $checkLoginState=true)
111
    {
112
        $this->plugin->klarnaLog('Entering Shopware_Controllers_Frontend_PaymentKlarna::createAccount', 3);
113
        $module = Shopware()->Modules()->Admin();
114
        $session = Shopware()->Session();
115
116
        $version = Shopware()->Config()->version;
117
        if ($version == '___VERSION___' || version_compare($version, '4.1.0', '>=')) {
118
            $encoder = Shopware()->PasswordEncoder()->getDefaultPasswordEncoderName();
119
        }
120
        
121
        $data = array();
122
123
        if ($order !== null && !empty($order['billing_address']['email'])) {
124
            $data['auth']['email'] = $order['billing_address']['email'];
125
            $data['auth']['password'] = $order['reference'];
126
        } else {
127
            $sessionId = Shopware()->SessionID();
128
            // email is only varchar(70) so we cut the sessionid
129
            //$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...
130
            $data['auth']['email'] = substr($sessionId, 0,49) . '@klarna.com';
131
            $data['auth']['password'] = $sessionId;
132
        }
133
        $data['auth']['accountmode'] = '1';
134
135
        $phone = $order['billing_address']['phone'];
136
        $data['billing']['phone'] = !empty($phone) ? $phone : ' ';
137
        $data['phone'] = !empty($phone) ? $phone : ' ';
138
        if (!empty($order['customer']['date_of_birth'])) {
139
            list($data['billing']['birthyear'], $data['billing']['birthmonth'], $data['billing']['birthday']) = explode(
140
                '-',
141
                $order['customer']['date_of_birth']
142
            );
143
        }
144
145
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->order:",4, $order);
146
        
147
        foreach (array('billing', 'shipping') as $type) {
148
            if (isset($order[$type . '_address'])) {
149
                $orderAddress = $order[$type . '_address'];
150
                if (isset($orderAddress['title'])) {
151
                    $data[$type]['salutation'] = $orderAddress['title'] == 'Frau' ? 'ms' : 'mr';
152
                } else {
153
                    $data[$type]['salutation'] = 'mr';
154
                }
155
                $data[$type]['firstname'] = $orderAddress['given_name'];
156
                $data[$type]['lastname'] = $orderAddress['family_name'];
157
                if (isset($orderAddress['street_name']) && $orderAddress['street_number']) {
158
                    if (version_compare(Shopware::VERSION, '5.0.0', '>=')) {
159
                        $data[$type]['street'] = $orderAddress['street_name'] . ' ' . $orderAddress['street_number'];
160 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...
161
                        $data[$type]['street'] = $orderAddress['street_name'];
162
                        $data[$type]['streetnumber'] = $orderAddress['street_number'];
163
                    }
164
                } else {
165
                    $data[$type]['street'] = $orderAddress['street_address'];
166
                    $data[$type]['streetnumber'] = ' ';
167
                }
168
                $data[$type]['zipcode'] = $orderAddress['postal_code'];
169
                $data[$type]['city'] = $orderAddress['city'];
170
                if (!empty($orderAddress['care_of'])) {
171
                    if ($orderAddress['street_name'] == 'Packstation') {
172
                        $data[$type]['postnumber'] = $orderAddress['care_of'];
173
                        $data[$type]['swagDhlPostnumber'] = $data[$type]['postnumber'];
174
                    } else {
175
                        $data[$type]['company'] = $orderAddress['care_of'];
176
                    }
177
                }
178
            } else {
179
                $data[$type]['salutation'] = 'mr';
180
                $data[$type]['firstname'] = 'Klarna Firstname';
181
                $data[$type]['lastname'] = 'Klarna Checkout';
182
                $data[$type]['street'] = 'Klarna Street';
183
                $data[$type]['streetnumber'] = ' ';
184
                $data[$type]['zipcode'] = '00000';
185
                $data[$type]['city'] = 'Klarna City ';
186
                $data[$type]['birthday'] = '0000-00-00';
187
                $data[$type]['phone'] = '00000000';
188
            }
189
            if (!isset($data[$type]['company'])) {
190
                $data[$type]['company'] = '';
191
            }
192
            $data[$type]['department'] = '';
193
194
            if (!empty($order[$type . '_address']['country'])) {
195
                $sql = 'SELECT id FROM s_core_countries WHERE countryiso=?';
196
                $countryId = Shopware()->Db()->fetchOne($sql, array($order[$type . '_address']['country']));
197
            } else {
198
                $countryId = $session['sCountry'];
199
            }
200
            // make sure country is set in case of lost sessions defualt to germany
201
            if (empty($countryId)){
202
                $countryId = 2;
203
            }            
204
205
            $data[$type]['country'] = $countryId;
206
        }
207
208
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->data AFTER ADDRESSES:",4,$data);
209
        $sql = 'SELECT id FROM s_core_paymentmeans WHERE name=?';
210
        $paymentId = Shopware()->Db()->fetchOne($sql, array('klarna_checkout'));
211
212
        if ($order !== null && !empty($order['billing_address']['email'])) {
213
            $shop = $this->get('shop');
214
            $shop = $shop->getMain() ?: $shop;
215
            $sql = 'SELECT id, email, `password` FROM `s_user` WHERE `email` LIKE ? AND `active` = 1 ';
216
            if ($shop->getCustomerScope()) {
217
                $sql .= "AND `subshopID` = {$shop->getId()} ";
218
            }
219
            $sql .= 'ORDER BY `accountmode`';
220
            $user = Shopware()->Db()->fetchRow($sql, array($data['auth']['email']));
221
            // First try login 
222
            if (!empty($user)) {
223
                $session->offsetSet('sUserMail', $user['email']);
224
                $session->offsetSet('sUserPassword', $user['password']);
225
                $session->offsetSet('sUserId', $user['id']);
226
            } else {
227
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->user Not Found in DB SQL was:" .$sql,1);                
228
            }
229
        }
230
231
        if ($checkLoginState) {
232
            // Check login status
233
            if (!empty($session->sUserId)) {
234
                if ($order !== null) {
235
                    $module->sSYSTEM->_POST = $data['shipping'];
236 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...
237
                        $userId = $session->offsetGet('sUserId');
238
                        $this->updateShipping($userId, $data['shipping']);
239
                    } else {
240
                        $module->sUpdateShipping();
241
                    }
242
                    $module->sSYSTEM->_POST = $data['billing'];
243 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...
244
                         $userId = $session->offsetGet('sUserId');
245
                         $this->updateBilling($userId, $data['billing']);
246
                    } else{
247
                        $module->sUpdateBilling();
248
                    }
249
                    unset($data['auth']['password']);
250
                    $module->sSYSTEM->_POST = $data['auth'];
251
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
252
                        $userId = $session->offsetGet('sUserId');
0 ignored issues
show
Unused Code introduced by
$userId 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...
253
                        $this->updateCustomer($data);
254
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->updateCustomer:",3, $data);                                                
255
                    } else{
256
                        $module->sUpdateAccount();
257
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->updateAccount:",3, $this->front->Request()->getPost());                                                                        
258
                    }
259
                } else {
260
                    /** @var Enlight_Controller_Front $front */
261
                    $front = $this->get('front');
262
                    $front->Request()->setPost(array());
263
                    $module->sSYSTEM->_POST = array('country' => $data['shipping']['country']);
264
                    $shippingId = $this->get('db')->fetchOne(
265
                        'SELECT id FROM s_user_shippingaddress WHERE userID = ?',
266
                        array($session->offsetGet('sUserId'))
267
                    );
268 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...
269
                        if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
270
                            $userId = $session->offsetGet('sUserId');
271
                            $this->updateShipping($userId, $data['shipping']);
272
                        } else {
273
                            $module->sUpdateShipping();
274
                        }
275
                    } else {
276
                        $module->sUpdateBilling();
277
                    }
278
                }
279
                $module->sSYSTEM->_POST = array('sPayment' => $paymentId);
280
                $module->sUpdatePayment();
281
            } else {
282
                $data['payment']['object'] = $module->sGetPaymentMeanById($paymentId);
283
                if (isset($encoder)) {
284
                    $data["auth"]["encoderName"] = $encoder;
285
                    $data["auth"]["password"] = Shopware()->PasswordEncoder()->encodePassword($data["auth"]["password"], $encoder);
286
                } else {
287
                    $data['auth']['password'] = md5($data['auth']['password']);
288
                }
289
                $session->sRegisterFinished = false;
290
                if (version_compare(Shopware::VERSION, '4.3.0', '>=') && version_compare(Shopware::VERSION, '5.2.0', '<')) {
291
                    $session->sRegister = $data;
292
                } elseif (version_compare(Shopware::VERSION, '4.3.0', '<')) {
293
                    $session->sRegister = new ArrayObject($data, ArrayObject::ARRAY_AS_PROPS);
294
                }
295
                try {
296
                    if (Shopware::VERSION === '___VERSION___' || version_compare(Shopware::VERSION, '5.2.0', '>=')) {
297
                        $newdata = $this->saveUser($data);
298
                        $module->sSYSTEM->_POST = $newdata['auth'];
299
                        $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...
300
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser:",3, $newdata);                        
301
                        // $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...
302
                    } else {
303
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser->Register:",3, $session->sRegister);                         
304
                        $module->sSaveRegister();
305
                        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->saveUser->RegisterFinished:",3, $session->offsetGet('sRegisterFinished')); 
306
                    }
307
                    
308
                } catch (\Exception $ex) { /* do nothing */
309
                    $this->klarnaLog("ERROR while creating User. Exception information:".$ex->getMessage(),1);
310
                    
311
                }
312
            }
313
            
314
        }
315
        
316
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::createAccount->data END OF METHOD:",4, $data);
317
    }
318
    
319
    /**
320
     * Saves a new user to the system.
321
     *
322
     * @param array $data
323
     */
324
    private function saveUser($data)
325
    {
326
327
        $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...
328
        $plain = array_merge($data['auth'], $data['shipping']);
329
330
        //Create forms and validate the input
331
        $customer = new Shopware\Models\Customer\Customer();
332
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\PersonalFormType', $customer);
333
        $form->submit($plain);
334
335
        $address = new Shopware\Models\Customer\Address();
336
        $form = $this->createForm('Shopware\Bundle\AccountBundle\Form\Account\AddressFormType', $address);
337
        $form->submit($plain);
338
339
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\ShopContextInterface $context */
340
        $context = $this->get('shopware_storefront.context_service')->getShopContext();
341
342
        /** @var Shopware\Bundle\StoreFrontBundle\Struct\Shop $shop */
343
        $shop = $context->getShop();
344
345
        /** @var Shopware\Bundle\AccountBundle\Service\RegisterServiceInterface $registerService */
346
        $registerService = $this->get('shopware_account.register_service');
347
        $registerService->register($shop, $customer, $address, $address);
348
349
        // get updated password; it is md5 randomized after register
350
        $getUser = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
351
		array('email' =>  $data['auth']['email'])
352
		);
353
354
       $data['auth']['password']= $getUser->getPassword();
355
       $data['auth']['passwordMD5']= $getUser->getPassword();
356
       $data['auth']['encoderName'] = 'md5';
357
        return $data;
358
    }
359
360
361
    /**
362
     * Endpoint for changing the main profile data
363
     */
364
    public function updateCustomer($data)
365
    {
366
        $data['birthdate'] = $data['billing']['birthyear'].'-'.$data['billing']['birthmonth'].'-'.$data['billing']['birthday'];
367
        $data['birthday'] = $data['birthdate'];    
368
        $data['email'] = $data['auth']['email'];
369
        $data['firstname'] = $data['billing']['firstname'];
370
        $data['lastname'] = $data['billing']['lastname'];
371
        unset ($data['shipping']);
372
        unset ($data['billing']);        
373
        
374
        $userId = $this->get('session')->get('sUserId');
375
376
        $customer = Shopware()->Models()->getRepository('Shopware\Models\Customer\Customer')->findOneBy(
377
		array('id' =>  $userId)
378
		);
379
        $customer->fromArray($data);
380
        Shopware()->Container()->get('shopware_account.customer_service')->update($customer);
381
    }
382
383
384
     /**
385
     * Updates the shipping address
386
     *
387
     * @param int $userId
388
     * @param array $shippingData
389
     */
390
    private function updateShipping($userId, $shippingData)
391
    {
392
        /** @var \Shopware\Components\Model\ModelManager $em */
393
        $em = $this->get('models');
394
395
        /** @var \Shopware\Models\Customer\Customer $customer */
396
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(array('id' => $userId));
397
398
        /** @var \Shopware\Models\Customer\Address $address */
399
        $addressold = $customer->getDefaultShippingAddress();
400
        $address = new \Shopware\Models\Customer\Address();
401
        
402
         /** @var \Shopware\Models\Country\Country $country */
403
        $country = $addressold->getCountry();
404
        $shippingData['country'] = $country;
405
        if ($shippingData['phone'] === null) {
406
            $shippingData['phone'] = ' ';
407
        }
408
        $address->fromArray($shippingData);
409
        try {
410
            $addressService = $this->get('shopware_account.address_service');
411
            $addressService->create($address, $customer);
412
            $addressService->setDefaultShippingAddress($address);
413
        } catch (Exception $ex) {
414
            $this->klarnaLog("ERROR while creating address via address service. Exception information:".$ex->getMessage(),1);
415
        }
416
        
417
    }
418
419
    /**
420
     * Updates the billing address
421
     *
422
     * @param int $userId
423
     * @param array $billingData
424
     */
425
    private function updateBilling($userId, $billingData)
426
    {
427
        /** @var \Shopware\Components\Model\ModelManager $em */
428
        $em = $this->get('models');
429
430
        /** @var \Shopware\Models\Customer\Customer $customer */
431
        $customer = $em->getRepository('Shopware\Models\Customer\Customer')->findOneBy(array('id' => $userId));
432
433
        /** @var \Shopware\Models\Customer\Address $address */
434
        $address = $customer->getDefaultBillingAddress();
435
        
436
         /** @var \Shopware\Models\Country\Country $country */
437
        $country = $address->getCountry();
438
        $billingData['country'] = $country;
439
        $address->fromArray($billingData);
440
441
        $this->get('shopware_account.address_service')->update($address);
442
    }
443
444
445
    /**
446
     * Needed to reset the session when the user logs in
447
     */
448
    public function loginAction()
449
    {
450
        Shopware()->Session()->offsetSet('KlarnaOrder', null);
451
        $this->redirect(array('controller' => 'payment_klarna', 'action' => 'express'));
452
    }
453
454
    /**
455
     * Return action method
456
     *
457
     * Reads the transactionResult and represents it for the customer.
458
     */
459
    public function returnAction()
460
    {
461
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction",3);
462
        if ($this->getPaymentShortName() != 'klarna_checkout') {
463
            $this->forward('index');
464
            return;
465
        }
466
        $transactionId = $this->Request()->getParam('transactionId');
467
        
468
        $connector = $this->plugin->getConnector();
469
470
        $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...
471
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->transactionId:\n".$transactionId,3);
472
        $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction->order:",4, $order);
473
        $orderNumber = '';
474
        
475
        try {
476
            $order->fetch();
477
478
            $this->createAccount($order);
479
            $this->plugin->updateOrderVariables();
480
481
            if ($order['status'] == 'checkout_complete') {
482
                $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: checkout_complete. Save oder if session values match.",3);
483
                if (Shopware()->Session()->offsetGet('KlarnaTransactionId') == null){
484
                    $this->plugin->klarnaLog("Entering Shopware_Controllers_Frontend_PaymentKlarna::returnAction: Session matches. Order will be saved",3);
485
                    Shopware()->Session()->offsetSet('KlarnaTransactionId', $transactionId );
486
                    $orderNumber = $this->saveOrder(
487
                        $order['reservation'],
488
                        $order['reference']
489
                    );
490
                    Shopware()->Session()->offsetSet('KlarnaTransactionId', null );                
491
                }
492
493
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::returnAction: checkout_complete. Check if Order was persisted in DB.",3);    
494
495
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::returnAction: checkout_complete. Searching for Order:",3);
496
                $this->checkKlarnaOrderExistsByReservation($order['reservation']);
497
                $this->checkKlarnaOrderExistsByReference($order['reference']);
498
                $this->checkKlarnaOrderExistsBySession(Shopware()->Session()->sUserId);
499
                $this->checkKlarnaOrderDetailsBySession(Shopware()->Session()->sUserId);
500
            }
501
502
            if (empty($orderNumber) && !empty($order['merchant_reference']['orderid1'])) {
503
                $orderNumber = $order['merchant_reference']['orderid1'];
504
            }
505
            $update = array();
506
            $update['merchant_reference'] = array(
507
                'orderid1' => (string) $orderNumber,
508
                'orderid2' => (string) $order['reference']
509
            );
510
            $order->update($update);   
511
           
512
            // Saves postnumber for dhl packstation
513
            if (!empty($orderNumber)
514
                && !empty($order['shipping_address']['care_of'])
515
                && $order['shipping_address']['street_name'] == 'Packstation'
516
                && $this->config->get('postnumberField')
517
            ) {
518
                $field = $this->config->get('postnumberField');
519
                $value = $order['shipping_address']['care_of'];
520
                $this->saveOrderAttribute($orderNumber, $field, $value);
521
            }
522
523
            if ($order['status'] == 'created' || $order['status'] == 'checkout_complete') {
524
                $this->saveOrderAttribute($orderNumber, 'swag_klarna_status', 'created');
525
                $this->savePaymentStatus(
526
                                $order['reservation'],
527
                                $order['reference'],
528
                                $this->config->get('statusId')
529
                            );                
530
                $this->redirect(array(
531
                    'controller' => 'checkout',
532
                    'action' => 'finish',
533
                    'sUniqueID' => $order['reference']
534
                ));
535
            } else {
536
                $this->redirect(array('controller' => 'checkout', 'action' => 'confirm'));
537
            }
538
        } catch (Exception $e) {
539
            Shopware()->Plugins()->Controller()->ViewRenderer()->setNoRender();
540
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::returnAction: Catch. Searching for Order:",3);   
541
            $this->checkKlarnaOrderExistsByReservation($order['reservation']);
542
            $this->checkKlarnaOrderExistsByReference($order['reference']);
543
            $this->checkKlarnaOrderExistsBySession(Shopware()->Session()->sUserId); 
544
            $this->checkKlarnaOrderDetailsBySession(Shopware()->Session()->sUserId); 
545
            echo "Entschuldigung, Ein Verbindungsfehler ist aufgetreten, bitte aktualisieren Sie die Seite";
546
        }            
547
    }
548
    
549
    /**
550
     * Method checks if certain klarna order exists or not
551
     * 
552
     * @param string $sessionID
553
     * @return bool
554
     */
555 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...
556
        $sql = '
557
            SELECT * FROM s_order
558
            WHERE userID=?
559
        ';
560
        
561
        $order = Shopware()->Db()->fetchAll($sql, array(
562
                $sessionID
563
        ));
564
        
565
        $orderExists = (empty($order)) ? false : true;
566
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession:",3);   
567
        if ($orderExists){
568
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsBySession: Order Found: ",3, $order);   
569
        }
570
        return $orderExists;
571
    }    
572
    
573
    /**
574
     * Method checks if certain klarna order exists or not
575
     * 
576
     * @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...
577
     * @param string $paymentUniqueId
578
     * @return bool
579
     */
580 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...
581
        $sql = '
582
            SELECT * FROM s_order
583
            WHERE temporaryID=?
584
        ';
585
        
586
        $order = Shopware()->Db()->fetchAll($sql, array(
587
                $paymentUniqueId
588
        ));
589
        
590
        $orderExists = (empty($order)) ? false : true;
591
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference:",3);   
592
        if ($orderExists){
593
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReference: Order Found: ",3, $order);   
594
        }
595
        return $orderExists;
596
    }
597
    
598
    /**
599
     * Method checks if certain klarna order exists or not
600
     * 
601
     * @param string $transactionId
602
     * @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...
603
     * @return bool
604
     */
605 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...
606
        $sql = '
607
            SELECT * FROM s_order
608
            WHERE transactionID=?
609
        ';
610
        
611
        $order = Shopware()->Db()->fetchAll($sql, array(
612
                $transactionId
613
        ));
614
        
615
        $orderExists = (empty($order)) ? false : true;
616
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation:",3);   
617
        if ($orderExists){
618
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderExistsByReservation: Order Found: ",3, $order);   
619
        }
620
        return $orderExists;
621
    }    
622
    
623
    /**
624
     * Method checks if certain klarna order exists or not
625
     * 
626
     * @param string $transactionId
627
     * @param string $paymentUniqueId
628
     * @return bool
629
     */
630
    protected function checkKlarnaOrderExists($transactionId, $paymentUniqueId) {
631
        $sql = '
632
            SELECT ordernumber FROM s_order
633
            WHERE transactionID=? AND temporaryID=?
634
            AND status!=-1 AND userID=?
635
        ';
636
        
637
        $orderNumber = Shopware()->Db()->fetchOne($sql, array(
638
                $transactionId,
639
                $paymentUniqueId,
640
                Shopware()->Session()->sUserId
641
        ));
642
        
643
        $orderExists = (empty($orderNumber)) ? false : true;
644
        
645
        return $orderExists;
646
    }
647
    
648
    /**
649
     * Method checks if certain klarna order exists or not
650
     * 
651
     * @param string $sessionID
652
     * @return bool
653
     */
654 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...
655
        $sql = '
656
            SELECT * FROM s_order
657
            LEFT JOIN s_order_details ON s_order.id = s_order_details.orderID
658
            WHERE userID=?
659
        ';
660
        
661
        $orderDetails = Shopware()->Db()->fetchAll($sql, array(
662
                $sessionID
663
        ));
664
        
665
        $orderExists = (empty($orderDetails)) ? false : true;
666
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession:",3);   
667
        if ($orderExists){
668
            $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::checkKlarnaOrderDetailsBySession: OrderDetails Found: ",3, $orderDetails);
669
        }
670
        return $orderExists;
671
    }     
672
673
    /**
674
     * Notify action method
675
     */
676
    public function pushAction()
677
    {
678
        $transactionId = $this->Request()->getParam('transactionId');
679
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction->transactionId:\n".$transactionId,3);
680
        $connector = $this->plugin->getConnector();
681
682
683
        $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...
684
        $order->fetch();
685
        $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction->order:",4, $order);
686
        
687
        // before continuing its mandatory to check if order has been persisted
688
        $orderExists = $this->checkKlarnaOrderExists($order['reservation'], $order['reference']);
689
        if (!$orderExists) {
690
            /**
691
             * @todo: Adding mechanism so that cancel signal will be send to klarna, if push notifications are over the limit of about 2 calls
692
             */
693
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction: checkout_complete. Order was not persisted in DB.",1);    
694
                $this->plugin->klarnaLog("Shopware_Controllers_Frontend_PaymentKlarna::pushAction: checkout_complete. Searching for Order:",1);   
695
                $this->checkKlarnaOrderExistsByReservation($order['reservation']);
696
                $this->checkKlarnaOrderExistsByReference($order['reference']);
697
                $this->checkKlarnaOrderExistsBySession(Shopware()->Session()->sUserId);  
698
                $this->checkKlarnaOrderDetailsBySession(Shopware()->Session()->sUserId); 
699
            return;
700
        }
701
        
702
        // create account will be called WITHOUT trying to login user due to this has been done while retrunAction
703
        $this->createAccount($order, false);
704
        $this->plugin->updateOrderVariables();
705
        
706
        if ($order['status'] == 'checkout_complete') {
707
            try {
708
                $orderNumber = $this->saveOrder(
709
                    $order['reservation'],
710
                    $order['reference'],
711
                    $this->config->get('statusId')
712
                );
713
714
                $this->saveOrderAttribute($orderNumber, 'swag_klarna_status', 'created');
715
            } catch (Exception $exc) {
716
                $this->plugin->klarnaLog("PROBLEM SAVING ORDER ON KLARNA PUSH UPDATE!:\n".$exc->getTraceAsString(),1);
717
            }
718
719
            $update = array();
720
            $update['status'] = 'created';
721
            $update['merchant_reference'] = array(
722
                'orderid1' => (string) $orderNumber,
723
                'orderid2' => (string) $order['reference']
724
            );
725
            $order->update($update);
726
        } elseif ($order['status'] == 'created') {
727
            $this->savePaymentStatus(
728
                $order['reservation'],
729
                $order['reference'],
730
                $this->config->get('statusId')
731
            );
732
        }
733
    }
734
735
    private function saveOrderAttribute($orderNumber, $field, $value)
736
    {
737
        try {
738
            $sql = "
739
                INSERT INTO s_order_attributes (orderID, `$field`)
740
                SELECT id, ? FROM s_order WHERE ordernumber = ?
741
                ON DUPLICATE KEY UPDATE `$field` = VALUES(`$field`)
742
            ";
743
            $this->get('db')->query($sql, array(
744
                $value,
745
                $orderNumber
746
            ));
747
        } catch (Exception $e) {
748
            $this->plugin->klarnaLog("PROBLEM SAVING ORDER ATTRIBUTES AFTER KLARNA PUSH!:\n".$e->getMessage(),1);
749
        }
750
    }
751
752
    /**
753
     * Save register form so we can use it if user change between klarna and register tab
754
     */
755
    public function saveFormDataAction()
756
    {
757
        $form = $this->Request()->getPost();
758
759
        //unset password from passed post
760
        unset($form['register']['personal']['password']);
761
762
        if (!empty($form)) {
763
            Shopware()->Session()->klarnaSavedRegister = $form;
764
        }
765
    }
766
767
    /**
768
     * Helper method to redirect the request to the proper page to set the payment into the customer account
769
     */
770
    public function setPaymentAction()
771
    {
772
        if ($this->Request()->isPost()) {
773
            $values = $this->Request()->getPost('register');
774
            $payment = $values['payment'];
775
        } else {
776
            $payment = $this->Request()->getParam('paymentId');
777
        }
778
779
        if (empty($payment)) {
780
            return;
781
        }
782
783
        $user = Shopware()->Modules()->Admin()->sGetUserData();
784
        if (empty($user) || $user['billingaddress']['lastname'] == 'Klarna Checkout') {
785
            $session = Shopware()->Session();
786
            $session->offsetSet('sPaymentID', $payment);
787
            $session->offsetUnset('sUserId');
788
            $session->offsetSet('sRegisterFinished', false);
789
790
            $this->redirect(
791
                array(
792
                    'controller' => 'register',
793
                    'action' => 'index',
794
                    'sTarget' => 'checkout',
795
                    'sTargetAction' => 'confirm'
796
                )
797
            );
798
        } else {
799
            $this->savePayment($payment);
800
            $this->redirect(
801
                array(
802
                    'controller' => 'checkout',
803
                    'action' => 'confirm'
804
                )
805
            );
806
        }
807
    }
808
809
    /**
810
     * This action is called when the user is not logged in and tries to change the payment from klarna to another payment.
811
     * Only used in responsive theme.
812
     */
813
    public function otherPaymentAction()
814
    {
815
        $userData = Shopware()->Modules()->Admin()->sGetUserData();
816
        $session = Shopware()->Session();
817
818
        // When the user is a valid user and accidentally calls this action, we don't want to reset his session
819
        if ($userData['billingaddress']['lastname'] == 'Klarna Checkout') {
820
            $session->offsetUnset('sUserId');
821
822
            //Remove all temporary klarna-users older than 24 hours
823
            Shopware()->Plugins()->Frontend()->SwagPaymentKlarna()->removeKlarnaUsers();
824
            $session->offsetSet('sRegisterFinished', false);
825
        }
826
        
827
            // reset country
828
            $session['sCountry'] = $userData['additional']['country']['id'];
829
            unset($session['sChangedCountry']);
830
831
        //Register-controller redirects to checkout by default when the user is logged in already.
832
        $this->redirect(array(
833
            'controller' => 'register',
834
            'klarnaRedirect' => 1,
835
            'sTarget' => 'checkout',
836
            'sTargetAction' => 'shippingPayment'
837
        ));
838
    }
839
840
    /**
841
     * Helper method to set the selected payment-method into the session to change it in the customer-account after logging in
842
     *
843
     * @param $paymentId
844
     * @throws Enlight_Exception
845
     */
846
    private function savePayment($paymentId)
847
    {
848
        $admin = Shopware()->Modules()->Admin();
849
        $admin->sSYSTEM->_POST['sPayment'] = $paymentId;
850
        $validation = $admin->sValidateStep3();
851
852
        if (!empty($validation['checkPayment']['sErrorMessages']) || empty($validation['sProcessed'])) {
853
            $this->View()->assign('sErrorFlag', $validation['checkPayment']['sErrorFlag']);
854
            $this->View()->assign('sErrorMessages', $validation['checkPayment']['sErrorMessages']);
855
        } else {
856
            $previousPayment = $admin->sGetUserData();
857
            $previousPayment = $previousPayment['additional']['user']['paymentID'];
858
859
            $previousPayment = $admin->sGetPaymentMeanById($previousPayment);
860
            if ($previousPayment['paymentTable']) {
861
                $deleteSQL = 'DELETE FROM '.$previousPayment['paymentTable'].' WHERE userID=?';
862
                Shopware()->Db()->query($deleteSQL, array(Shopware()->Session()->offsetGet('sUserId')));
863
            }
864
865
            $admin->sUpdatePayment();
866
867
            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...
868
                $validation['sPaymentObject']->savePaymentData(Shopware()->Session()->offsetGet('sUserId'), $this->Request());
869
            }
870
        }
871
    }
872
    
873
    protected function isUserLoggedIn($session)
874
    {        
875
         return (isset($session->sUserId) && !empty($session->sUserId));
876
    }    
877
}
878