Passed
Push — master ( 98c61b...80c098 )
by Mario
04:44
created

Bootstrap::checkValidKlarnaCountry()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 3
nop 1
dl 0
loc 18
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * Shopware
4
 * Copyright © 2015 shopware AG
5
 *
6
 * According to our dual licensing model, this program can be used either
7
 * under the terms of the GNU Affero General Public License, version 3,
8
 * or under a proprietary license.
9
 *
10
 * The texts of the GNU Affero General Public License with an additional
11
 * permission and of our proprietary license can be found at and
12
 * in the LICENSE file you have received along with this program.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17
 * GNU Affero General Public License for more details.
18
 *
19
 * "Shopware" is a registered trademark of shopware AG.
20
 * The licensing of the program under the AGPLv3 does not imply a
21
 * trademark license. Therefore any rights, title and interest in
22
 * our trademarks remain entirely with us.
23
 */
24
25
use Doctrine\DBAL\Connection;
26
use Shopware\Components\StreetSplitService;
27
28
# Load dummy interface CSRFWhitelistAware for SW < 5.2
29
require_once __DIR__ . '/Components/CSRFWhitelistAware.php';
30
31
/**
32
 * Shopware Klarna Plugin
33
 */
34
class Shopware_Plugins_Frontend_SwagPaymentKlarna_Bootstrap extends Shopware_Components_Plugin_Bootstrap
35
{
36
    /**
37
     * Get cached countries
38
     * @var array
39
     */
40
    private $countries = array();
41
42
    /**
43
     * The klarna payment object.
44
     * @var \Shopware\Models\Payment\Payment
45
     */
46
    private $klarnaPayment = null;
47
    
48
    /**
49
     * Instance of API-Object
50
     * @var object
51
     */
52
    private $klarnaService = null;
53
54
    /**
55
     * Instance of klarna address object
56
     * @var object
57
     */
58
    private $klarnaAddr = null;
59
60
    /**
61
     * @return array
62
     */
63
    public function install($isUpdate = false)
64
    {
65
        $this->createMyEvents();
66
        if (!$isUpdate) {
67
            $this->createMyPayment();
68
        }
69
        $this->createMyForm();
70
        $this->createMyTranslations();
71
        $this->createMyAttributes();
72
73
        $aReturn = array(
74
            'success' => true,
75
            'invalidateCache' => array('backend')
76
        );
77
        
78
        return $aReturn;
79
    }
80
81
    /**
82
     * @param string $version
83
     * @return bool
84
     */
85
    public function update($version)
86
    {
87
        if ($version == '0.0.1') {
88
            return false;
89
        }
90
91
        if (version_compare($version, '2.0.0', '<')) {
92
            $em = $this->get('models');
93
            $form = $this->Form();
94
            if ($form->getElement('hideCheckoutSteps')) {
95
                $em->remove($form->getElement('hideCheckoutSteps'));
96
            }
97
            if ($form->getElement('expressButton')) {
98
                $em->remove($form->getElement('expressButton'));
99
            }
100
            if ($form->getElement('expressButtonLayer')) {
101
                $em->remove($form->getElement('expressButtonLayer'));
102
            }
103
            if ($form->getElement('noAccountCheckout')) {
104
                $em->remove($form->getElement('noAccountCheckout'));
105
            }
106
            $em->flush();
107
108
            $this->updatePayment();
109
        }
110
111
        return $this->install(true);
112
    }
113
114
    /**
115
     * @return bool
116
     */
117
    public function uninstall()
118
    {
119
        try {
120
            $this->get('models')->removeAttribute(
121
                's_order_attributes',
122
                'swag_klarna',
123
                'status'
124
            );
125
            $this->get('models')->removeAttribute(
126
                's_order_attributes',
127
                'swag_klarna',
128
                'invoice_number'
129
            );
130
            $this->get('models')->removeAttribute(
131
                's_order_details_attributes',
132
                'swag_klarna',
133
                'invoice_number'
134
            );
135
            $this->get('models')->generateAttributeModels(
136
                array(
137
                    's_order_attributes',
138
                    's_order_details_attributes'
139
                )
140
            );
141
        } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
142
        }
143
144
        return true;
145
    }
146
147
    /**
148
     * @param string $name
149
     * @return mixed
150
     */
151
    public function get($name)
152
    {
153
        if (version_compare(Shopware::VERSION, '4.2.0', '<') && Shopware::VERSION != '___VERSION___') {
154
            $name = ucfirst($name);
155
            return $this->Application()->Bootstrap()->getResource($name);
156
        }
157
158
        return parent::get($name);
159
    }
160
161
    /**
162
     * Fetches and returns klarna payment row instance.
163
     *
164
     * @return \Shopware\Models\Payment\Payment
165
     */
166
    public function getPayment()
167
    {
168
        if ($this->klarnaPayment === null) {
169
            $this->klarnaPayment = $this->Payments()->findOneBy(
170
                array('name' => 'klarna_checkout')
171
            );
172
        }
173
174
        return $this->klarnaPayment;
175
    }
176
177
    /**
178
     * @return \Klarna_Checkout_Connector
179
     */
180
    public function getConnector()
181
    {
182
        return $this->Application()->KlarnaCheckoutConnector();
183
    }
184
185
    /**
186
     * @return \Klarna
187
     */
188
    public function getService()
189
    {
190
        /** @var Klarna $service */
191
        $service = $this->Application()->KlarnaService();
192
        $service->setActivateInfo('flags', KlarnaFlags::RSRV_SEND_BY_EMAIL);
193
        $service->setVersion($this->buildKlarnaVersion($service));
194
        $service->config(
195
            $this->Config()->get('merchantId'),
196
            $this->Config()->get('sharedSecret'),
197
            KlarnaCountry::DE,
198
            KlarnaLanguage::DE,
199
            KlarnaCurrency::EUR,
200
            $this->Config()->get('testDrive') ? Klarna::BETA : Klarna::LIVE,
201
            'pdo',
202
            array(
0 ignored issues
show
Documentation introduced by
array('table' => 's_klar...>Db()->getConnection()) is of type array<string,?,{"table":"string","pdo":"?"}>, but the function expects a string.

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...
203
                'table' => 's_klarna_pclasses',
204
                'pdo' => $this->Application()->Db()->getConnection()
205
            )
206
        );
207
208
        return $service;
209
    }
210
211
    /**
212
     * Activate the plugin klarna plugin.
213
     * Sets the active flag in the payment row.
214
     *
215
     * @return bool
216
     */
217
    public function enable()
218
    {
219
        $payment = $this->getPayment();
220
        if ($payment !== null) {
221
            $payment->setActive(true);
222
            $this->get('models')->flush($payment);
223
        }
224
225
        return array(
226
            'success' => true,
227
            'invalidateCache' => array('backend', 'frontend')
228
        );
229
    }
230
231
    /**
232
     * Disable plugin method and sets the active flag in the payment row
233
     *
234
     * @return bool
235
     */
236
    public function disable()
237
    {
238
        $payment = $this->getPayment();
239
        if ($payment !== null) {
240
            $payment->setActive(false);
241
            $this->get('models')->flush($payment);
242
        }
243
244
        return true;
245
    }
246
    
247
    /**
248
     * Returns an instance of klarna object
249
     * 
250
     * @param void
251
     * @return \Klarna
252
     */
253
    public function getKLarnaService() {
254
        if ($this->klarnaService === null) {
255
            require_once __DIR__ . '/Components/Klarna/Klarna.php';
256
            require_once __DIR__ . '/Components/Klarna/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc';
257
            $this->klarnaService = new Klarna();
258
        }
259
260
        return $this->klarnaService;
261
    }
262
    
263
    /**
264
     * Returns an instance of klarna address object
265
     * 
266
     * @param void
267
     * @return object
268
     */
269
    public function getKlarnaAddr() {
270
        if ($this->klarnaAddr === null) {
271
            $this->klarnaAddr = new KlarnaAddr();
272
        }
273
        
274
        return $this->klarnaAddr;
275
    }
276
277
    /**
278
     * Creates and subscribe the events and hooks.
279
     */
280
    protected function createMyEvents()
281
    {
282
        // BACKEND
283
        $this->subscribeEvent(
284
            'Enlight_Controller_Action_PostDispatch_Backend_Order',
285
            'onLoadOrderBackendModule'
286
        );
287
        $this->subscribeEvent(
288
            'Enlight_Controller_Action_PostDispatch_Backend_Payment',
289
            'onLoadPaymentBackendModule'
290
        );
291
292
        $this->subscribeEvent(
293
            'Enlight_Controller_Dispatcher_ControllerPath_Backend_PaymentKlarna',
294
            'onGetControllerPathBackend'
295
        );
296
297
        // FRONTEND
298
        $this->subscribeEvent(
299
            'Enlight_Controller_Dispatcher_ControllerPath_Frontend_PaymentKlarna',
300
            'onGetControllerPathFrontend'
301
        );
302
        $this->subscribeEvent(
303
            'Enlight_Controller_Action_Frontend_Checkout_Express',
304
            'onCheckoutExpress'
305
        );
306
307
        $this->subscribeEvent(
308
            'Enlight_Controller_Action_Frontend_Checkout_saveShippingKlarna',
309
            'onCheckoutSaveShippingKlarna'
310
        );
311
312
        $this->subscribeEvent(
313
            'Enlight_Controller_Action_PostDispatch',
314
            'onPostDispatch',
315
            110
316
        );
317
318
        // CONNECTOR
319
        $this->subscribeEvent(
320
            'Enlight_Bootstrap_InitResource_KlarnaCheckoutConnector',
321
            'onInitResourceKlarnaCheckoutConnector'
322
        );
323
324
        // SERVICES
325
        $this->subscribeEvent(
326
            'Enlight_Bootstrap_InitResource_KlarnaService',
327
            'onInitResourceKlarnaService'
328
        );
329
330
        $this->subscribeEvent(
331
            'Enlight_Bootstrap_InitResource_StreetSplitService',
332
            'onGetStreetSplitService'
333
        );
334
335
        $this->subscribeEvent(
336
            'Enlight_Controller_Action_PostDispatch_Frontend_Register',
337
            'onPostDispatchFrontendRegister'
338
        );
339
340
        $this->subscribeEvent(
341
            'Shopware\Models\Customer\Repository::getListQueryBuilder::after',
342
            'onAfterGetCustomerListQueryBuilder'
343
        );
344
345
        $this->subscribeEvent(
346
            'Theme_Compiler_Collect_Plugin_Javascript',
347
            'addJsFiles'
348
        );
349
350
        // LESS
351
        // Subscribe the needed event for less merge and compression
352
        $this->subscribeEvent(
353
            'Theme_Compiler_Collect_Plugin_Less',
354
            'addLessFiles'
355
        );
356
357
        #########
358
        # HOOKS   #
359
        #########
360
361
        $this->subscribeEvent(
362
            'Shopware_Controllers_Backend_Payment::updatePaymentsAction::before',
363
            'onBeforeUpdatePayment'
364
        );
365
        
366
        $this->subscribeEvent(
367
            'Shopware_Controllers_Backend_Order::saveAction::after',
368
            'onBackendOrderSaveAfter'
369
        );    
370
        $this->subscribeEvent(
371
            'Shopware_Controllers_Backend_Order::deleteAction::after',
372
            'onBackendOrderDeleteAfter'
373
        );          
374
        
375
    }
376
377
    /**
378
     * Method will be triggered on clicking save on order details
379
     * 
380
     * @param Enlight_Hook_HookArgs $args
381
     * @return void
382
     */
383
    public function onBackendOrderSaveAfter(Enlight_Hook_HookArgs $args) {
384
        $orderDataRaw = $args->getSubject()->Request()->getPost();
385
        $orderId = $orderDataRaw['id'];
386
        $paymentName = $orderDataRaw['payment'][0]['name'];
387
388
        $orderStatus = $this->getOrderStatusById($orderId);
389
390
        $validUpdateDataToKlarna = (
391
            $orderStatus != 'activate' &&
392
            (
393
                $paymentName == 'klarna_checkout' ||
394
                $paymentName == 'klarna_account' ||
395
                $paymentName == 'klarna_invoice'
396
            )
397
        );
398
399
        if ($validUpdateDataToKlarna) {
400
            
401
            $klarnaService = $this->getService();
402
403
            $klarnaAddrBilling = $this->getKlarnaAddrByRawOrderData($orderDataRaw,'billing');
404
            $klarnaAddrShipping = $this->getKlarnaAddrByRawOrderData($orderDataRaw,'shipping');
405
406
            $transactionId = $orderDataRaw['transactionId'];
407
            
408
            $klarnaService->setAddress(KlarnaFlags::IS_BILLING, $klarnaAddrBilling);
0 ignored issues
show
Security Bug introduced by
It seems like $klarnaAddrBilling defined by $this->getKlarnaAddrByRa...rderDataRaw, 'billing') on line 403 can also be of type false; however, Klarna::setAddress() does only seem to accept object<KlarnaAddr>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
409
            $klarnaService->setAddress(KlarnaFlags::IS_SHIPPING, $klarnaAddrShipping);
0 ignored issues
show
Security Bug introduced by
It seems like $klarnaAddrShipping defined by $this->getKlarnaAddrByRa...derDataRaw, 'shipping') on line 404 can also be of type false; however, Klarna::setAddress() does only seem to accept object<KlarnaAddr>, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
410
            try {
411
                $klarnaService->update($transactionId);
412
            } catch (Exception $e) {
413
                throw new Exception($e->getMessage());
414
            }
415
        }
416
    }
417
418
    /**
419
     * @param $orderId
420
     * @return string
421
     */
422
    protected function getOrderStatusById($orderId)
423
    {
424
        $klarnaOrderStatus = Shopware()->Db()->fetchOne('SELECT swag_klarna_status FROM s_order_attributes WHERE orderID = ?', [$orderId]);
425
426
        return $klarnaOrderStatus;
427
    }
428
429
    
430
    /**
431
     * Method will be triggered on clicking delete on order overview
432
     * 
433
     * @param Enlight_Hook_HookArgs $args
434
     * @return void
435
     */
436
    public function onBackendOrderDeleteAfter(Enlight_Hook_HookArgs $args) {
437
        $orderDataRaw = $args->getSubject()->Request()->getPost();
438
        $paymentName = $orderDataRaw['payment'][0]['name'];
439
        
440
        if ($paymentName == 'klarna_checkout') {
441
            
442
            $klarnaService = $this->getService();
443
            $transactionId = $orderDataRaw['transactionId'];
444
            try {
445
                $klarnaService->cancelReservation($transactionId);
446
            } catch (Exception $e) {
447
                throw new Exception($e->getMessage());
448
            }
449
        }
450
    }    
451
    
452
    
453
    /**
454
     * Hook to change the absolute media-path to a normalized virtual path.
455
     * @param Enlight_Hook_HookArgs $args
456
     */
457
    public function onBeforeUpdatePayment(Enlight_Hook_HookArgs $args)
458
    {
459
        if (!$this->assertMinimumVersion('5.1')) {
460
            return;
461
        }
462
463
        /** @var Zend_Controller_Request_Http $request */
464
        $request = $args->getSubject()->Request();
465
        $attributes = $request->getParam('attribute');
466
        $attribute = reset($attributes);
467
468
        if (empty($attribute['swagKlarnaKlarnaMedia'])) {
469
            return;
470
        }
471
472
        $mediaService = $this->get('shopware_media.media_service');
473
        $attribute['swagKlarnaKlarnaMedia'] = $mediaService->normalize($attribute['swagKlarnaKlarnaMedia']);
474
        $attributes[0] = $attribute;
475
        $request->setParam('attribute', $attributes);
476
    }
477
478
    /**
479
     * Needed to implement an additional "where"-condition to filter temporary klarna-customers, so they won't be shown
480
     * in the backend anymore.
481
     *
482
     * @param Enlight_Hook_HookArgs $args
483
     */
484
    public function onAfterGetCustomerListQueryBuilder(Enlight_Hook_HookArgs $args)
485
    {
486
        /** @var \Doctrine\DBAL\Query\QueryBuilder $builder */
487
        $builder = $args->getReturn();
488
489
        $builder->andWhere('billing.lastName != :lastName')->setParameter('lastName', 'Klarna Checkout');
490
491
        $args->setReturn($builder);
492
    }
493
494
     public function onGetStreetSplitService()
495
    {
496
        $this->Application()->Loader()->registerNamespace(
497
            'Shopware\Components',
498
            __DIR__ . '/Components/'
499
        );
500
501
        return new StreetSplitService();
502
    }
503
    
504
    /**
505
     * Logs a message
506
     * 
507
     * @param string $message
508
     * @param int $logLevelMessage
509
     * @param mixed $mPrintableElement
510
     * @return void
511
     */
512 View Code Duplication
    public function klarnaLog($message, $logLevelMessage=1, $mPrintableElement=null) {
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...
513
        $configname = 'klarnaLogLevel';
514
        $elementId = Shopware()->Db()->fetchOne('SELECT id FROM s_core_config_elements WHERE name = ?', [$configname]);
515
        $logLevelConfigSetting = Shopware()->Db()->fetchOne('SELECT value FROM s_core_config_values WHERE element_id = ?', [$elementId]);
516
        $logLevelConfigSetting = unserialize($logLevelConfigSetting);
517
        $logLevelSetting = (is_numeric($logLevelConfigSetting) && $logLevelConfigSetting >=0 && $logLevelConfigSetting <=4) ? (int)$logLevelConfigSetting : 1;
518
        
519
        if ($logLevelMessage <= $logLevelSetting) {
520
            $prefix = "[".date('Y-m-d H:i:s')."] ";
521
            $debugBacktrace = '';
522
            if ($logLevelSetting >= 4) {
523
                $debugBacktrace = print_r(debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS),true);
524
            }
525
            $sPrintableElementMessage = '';
526
            if ($mPrintableElement !== null) {
527
                $sPrintableElementMessage = print_r($mPrintableElement,true);
528
            }
529
            $fullMessage = $prefix.$message."\n".$sPrintableElementMessage.$debugBacktrace;
530
            $shopPath = Shopware()->DocPath();
531
            $logfilePath = $shopPath.'/var/log/klarnaTrace.log';
532
            $fileHandler = fopen($logfilePath,'a');
533
            fwrite($fileHandler, $fullMessage);
534
            fclose($fileHandler);
535
        }
536
    }
537
    
538
    /**
539
     * Method returns matching address parts by address type
540
     * 
541
     * @param array $orderDataRaw
542
     * @param string $type
543
     */
544
    protected function getKlarnaAddrByRawOrderData($orderDataRaw, $type) {
545
        $klarnaAddr = false;
546
        $baseData = (isset($orderDataRaw[$type][0])) ? $orderDataRaw[$type][0] : false;
547
        $baseData = $this->convertEncoding($baseData);
548
        
549
        if ($baseData) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $baseData of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
550
            $addressParts = $this->fetchStreetAndHouseNumber($baseData);
551
552
            $manager = $this->get('models');
553
            $repository = 'Shopware\Models\Country\Country';
554
            $repository = $manager->getRepository($repository);
555
            $country = $repository->findOneBy(array('id' => $baseData['countryId']));
556
            $countryiso = $country->getIso();
557
558
            $klarnaAddr =  new KlarnaAddr();
559
            $klarnaAddr->setEmail($orderDataRaw['customerEmail']);
560
            $klarnaAddr->setFirstName($baseData['firstName']);
561
            $klarnaAddr->setLastName($baseData['lastName']);
562
            $klarnaAddr->setTelno($baseData['phone']);
563
            $klarnaAddr->setStreet($addressParts['street']);
564
            $klarnaAddr->setHouseNumber($addressParts['streetnr']);
565
            $klarnaAddr->setHouseExt($addressParts['streetnr_extension']);
566
            $klarnaAddr->setCompanyName($baseData['company']);
567
            $klarnaAddr->setCareof($baseData['department']);
568
            $klarnaAddr->setZipCode($baseData['zipCode']);
569
            $klarnaAddr->setCity($baseData['city']);
570
            $klarnaAddr->setCountry($countryiso);
571
        }
572
573
        $this->klarnaLog('Update order address from backend with following address data:',3,$klarnaAddr);
574
        return $klarnaAddr;
575
    }
576
577
578
    /**
579
     * Method splits street, streetnr and streetnr extension from basestring
580
     *
581
     * @param array $baseData
582
     * @return array
583
     */
584
    protected function fetchStreetAndHouseNumber($baseData) {
585
586
        $addressParts = explode(' ', $baseData['street']);
587
        $index = 0;
588
        $street = $streetnr = '';
589
        $houseNumberFound = false;
590
591
        foreach ($addressParts as $addressPart) {
592
            if (!$houseNumberFound) {
593
                // check if current addresspart is numeric
594
                $houseNumberFound = is_numeric($addressPart);
595
            }
596
597
            $index++;
598
            if ($index == count($addressParts) || $houseNumberFound) {
599
                // at least last element should be streetnr
600
                if (!empty($streetnr)) $streetnr .= ' ';
601
                $streetnr .= (string)$addressPart;
602
            }
603
            else  {
604
                $street .= (string)' '.$addressPart;
605
            }
606
        }
607
608
        $streetnr_extension = '';
609
        if (!empty($baseData['additionalAddressLine1'])) {
610
            $streetnr_extension .= $baseData['additionalAddressLine1'];
611
        }
612
        if (!empty($baseData['additionalAddressLine2'])) {
613
            $streetnr_extension .= "\n".$baseData['additionalAddressLine2'];
614
        }
615
616
        $return = array(
617
            'street' => $street,
618
            'streetnr' => $streetnr,
619
            'streetnr_extension' => $streetnr_extension,
620
        );
621
622
        return $return;
623
    }
624
    
625
626
    /**
627
     * Converts encoding in all string fields of an array
628
     * 
629
     * @param array $data
630
     * @return array
631
     */
632
    protected function convertEncoding($data) {
633
        $out = array();
634
        foreach ($data as $key=>$value) {
635
            if (is_string($value)) {
636
                $value = mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
637
                // $value = utf8_decode($value);
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
638
            }
639
            
640
            $out[$key] = $value;
641
        }
642
        
643
        return $out;
644
    }
645
646
    /**
647
     * Creates and save the payment row.
648
     */
649
    protected function createMyPayment()
650
    {
651
        /** @var \Shopware\Components\Model\ModelManager $manager */
652
        $manager = $this->get('models');
653
        $repository = 'Shopware\Models\Country\Country';
654
        $repository = $manager->getRepository($repository);
655
        $countries = array(
656
            $repository->findOneBy(array('iso' => 'SE')),
657
            $repository->findOneBy(array('iso' => 'DE')),
658
            $repository->findOneBy(array('iso' => 'NO')),
659
            $repository->findOneBy(array('iso' => 'FI')),
660
            $repository->findOneBy(array('iso' => 'AT'))
661
        );
662
        $this->createPayment(
663
            array(
664
                'name' => 'klarna_checkout',
665
                'description' => $this->getLabel(),
666
                'action' => 'payment_klarna',
667
                'additionalDescription' => '',
668
                'countries' => $countries
669
            )
670
        );
671
    }
672
673
    /**
674
     * Creates and stores the payment config form.
675
     */
676
    protected function createMyForm()
677
    {
678
        $form = $this->Form();
679
680
        // API settings
681
        $form->setElement(
682
            'boolean',
683
            'testDrive',
684
            array(
685
                'label' => 'Testmodus aktvieren',
686
                'value' => false,
687
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
688
                'position' => 0
689
            )
690
        );
691
692
        $form->setElement(
693
            'text',
694
            'merchantId',
695
            array(
696
                'label' => 'API-HändlerID (EID)',
697
                'required' => true,
698
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
699
                'position' => 1
700
            )
701
        );
702
703
        $form->setElement(
704
            'text',
705
            'sharedSecret',
706
            array(
707
                'label' => 'API-Secret (sharedsecret)',
708
                'required' => true,
709
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
710
                'position' => 2
711
            )
712
        );
713
714
        $form->setElement(
715
            'number',
716
            'termSiteId',
717
            array(
718
                'label' => 'Shopseite mit den Geschäftsbedingungen',
719
                'value' => 4,
720
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
721
                'position' => 3
722
            )
723
        );
724
725
        $form->setElement(
726
            'boolean',
727
            'allowSeparateShippingAddress',
728
            array(
729
                'label' => 'Abweichende Lieferadresse erlauben',
730
                'value' => true,
731
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
732
                'position' => 4
733
            )
734
        );
735
736
        $form->setElement(
737
            'boolean',
738
            'supportPackstation',
739
            array(
740
                'label' => 'DHL Packstation unterstützen',
741
                'value' => false,
742
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
743
                'position' => 5,
744
                'helpText' => 'Die abweichende Lieferadresse muss erlaubt sein'
745
            )
746
        );
747
748
        $form->setElement(
749
            'text',
750
            'postnumberField',
751
            array(
752
                'label' => 'Alternatives Feld für die DHL-Postnummer',
753
                'value' => 'attribute1',
754
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
755
                'position' => 6
756
            )
757
        );
758
759
        $form->setElement(
760
            'boolean',
761
            'mandatoryPhone',
762
            array(
763
                'label' => 'Telefonummer als Pflichtfeld',
764
                'value' => false,
765
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
766
                'position' => 7
767
            )
768
        );
769
770
        $form->setElement(
771
            'boolean',
772
            'mandatoryBirthday',
773
            array(
774
                'label' => 'Geburtsdatum als Pflichtfeld',
775
                'value' => false,
776
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
777
                'position' => 8
778
            )
779
        );
780
781
        $form->setElement(
782
            'boolean',
783
            'disableAutofocus',
784
            array(
785
                'label' => 'Autofokus deaktivieren',
786
                'value' => false,
787
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
788
                'position' => 9
789
            )
790
        );
791
792
        $form->setElement(
793
            'boolean',
794
            'showKlarnaButton',
795
            array(
796
                'label' => 'Klarna Checkout-Button anzeigen',
797
                'value' => true,
798
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
799
                'position' => 10
800
            )
801
        );
802
803
        $form->setElement(
804
            'boolean',
805
            'preFillCheckout',
806
            array(
807
                'label' => 'Klarna Checkout für registrierte Kunden vorausfüllen',
808
                'value' => true,
809
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
810
                'position' => 11
811
            )
812
        );
813
814
        $form->setElement(
815
            'color',
816
            'checkoutButtonColor',
817
            array(
818
                'label' => 'Checkout Button Farbe',
819
                'value' => null,
820
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
821
                'position' => 12
822
            )
823
        );
824
825
        $form->setElement(
826
            'color',
827
            'checkoutButtonTextColor',
828
            array(
829
                'label' => 'Checkout Buttontext Farbe',
830
                'value' => null,
831
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
832
                'position' => 13
833
            )
834
        );
835
836
        $form->setElement(
837
            'color',
838
            'checkoutCheckboxColor',
839
            array(
840
                'label' => 'Checkout Checkbox Farbe',
841
                'value' => null,
842
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
843
                'position' => 14
844
            )
845
        );
846
847
        $form->setElement(
848
            'color',
849
            'checkoutCheckboxCheckmarkColor',
850
            array(
851
                'label' => 'Checkout Checkbox Häckchen Farbe',
852
                'value' => null,
853
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
854
                'position' => 15
855
            )
856
        );
857
858
        $form->setElement(
859
            'color',
860
            'checkoutHeaderColor',
861
            array(
862
                'label' => 'Checkout Header Farbe',
863
                'value' => null,
864
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
865
                'position' => 16
866
            )
867
        );
868
869
        $form->setElement(
870
            'color',
871
            'checkoutLinkColor',
872
            array(
873
                'label' => 'Checkout Link Farbe',
874
                'value' => null,
875
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
876
                'position' => 17
877
            )
878
        );
879
880
        $form->setElement(
881
            'boolean',
882
            'KlarnaExternalPayments',
883
            array(
884
                'label' => 'Externe Zahlungsarten im Klarna Checkout darstellen',
885
                'value' => null,
886
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
887
                'helpText' => 'Ihr Klarna-Konto muss für diese Funktion freigeschaltet werden',
888
                'position' => 18
889
            )
890
        );
891
892
        $form->setElement(
893
            'select',
894
            'displayType',
895
            array(
896
                'label' => 'Klarna Checkout Darstellungs-Art',
897
                'value' => 1,
898
                'store' => array(
899
                    array(1, 'Tab-Darstellung'),
900
                    array(2, 'Nur Klarna Checkout-Darstellung'),
901
                    array(3, 'Einseiten-Darstellung')
902
                ),
903
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
904
                'position' => 19
905
            )
906
        );
907
908
        $form->setElement(
909
            'boolean',
910
            'showB2bSelect',
911
            array(
912
                'label' => 'B2B-Auswahl anzeigen',
913
                'value' => true,
914
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
915
                'helpText' => 'In dem Klarna Checkout wird eine Auswahl "Privatkunde / Firma" angezeigt',
916
                'position' => 20
917
            )
918
        );
919
920
        $form->setElement(
921
            'boolean',
922
            'showLoginPanel',
923
            array(
924
                'label' => 'Login-Formular anzeigen',
925
                'value' => true,
926
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
927
                'helpText' => 'In dem Klarna Checkout wird ein Login-Formular angezeigt',
928
                'position' => 21
929
            )
930
        );
931
932
        $form->setElement(
933
            'boolean',
934
            'showMiniBasket',
935
            array(
936
                'label' => 'Warenkorb anzeigen',
937
                'value' => true,
938
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
939
                'helpText' => 'In dem Klarna Checkout wird eine kleine Übersicht des Warenkorbs angezeigt',
940
                'position' => 22
941
            )
942
        );
943
944
        $form->setElement(
945
            'boolean',
946
            'showDispatch',
947
            array(
948
                'label' => 'Lieferland & Versandarten anzeigen',
949
                'value' => true,
950
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
951
                'helpText' => 'In dem Klarna Checkout wird eine Lieferland- sowie Versandarten-Auswahl angezeigt',
952
                'position' => 23
953
            )
954
        );
955
956
        $form->setElement(
957
            'select',
958
            'positionOrder',
959
            array(
960
                'label' => 'Reihenfolge der Elemente',
961
                'value' => 1,
962
                'store' => array(
963
                    array(1, 'Login-Formular, Mini-Warenkorb, Versandauswahl, Zahlungsauswahl'),
964
                    array(2, 'Login-Formular, Mini-Warenkorb, Zahlungsauswahl, Versandauswahl'),
965
                    array(3, 'Versandauswahl, Zahlungsauswahl, Login-Formular, Mini-Warenkorb'),
966
                    array(4, 'Zahlungsauswahl, Versandauswahl, Login-Formular, Mini-Warenkorb')
967
                ),
968
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
969
                'helpText' => 'Die \'Zahlungsauswahl\' wird nur in der \'Einseitig\'-Darstellung angezeigt.',
970
                'position' => 24
971
            )
972
        );
973
974
        $form->setElement(
975
            'boolean',
976
            'partPaymentWidget',
977
            array(
978
                'label' => 'Teilzahlungs-Widget auf der Detailseite anzeigen',
979
                'value' => true,
980
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
981
                'position' => 25
982
            )
983
        );
984
985
        $form->setElement(
986
            'boolean',
987
            'convertShippingFee',
988
            array(
989
                'label' => 'Versandkosten in eine Bestellposition umwandeln',
990
                'value' => true,
991
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
992
                'position' => 26
993
            )
994
        );
995
996
        $form->setElement(
997
            'select',
998
            'statusId',
999
            array(
1000
                'label' => 'Zahlstatus nach der Bestellung',
1001
                'value' => 18,
1002
                'store' => 'base.PaymentStatus',
1003
                'displayField' => 'description',
1004
                'valueField' => 'id',
1005
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
1006
                'position' => 27
1007
            )
1008
        );
1009
1010
        $form->setElement(
1011
            'select',
1012
            'activateStatusId',
1013
            array(
1014
                'label' => 'Zahlungsstatus nach der Aktivierung',
1015
                'value' => 12,
1016
                'store' => 'base.PaymentStatus',
1017
                'displayField' => 'description',
1018
                'valueField' => 'id',
1019
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
1020
                'position' => 28
1021
            )
1022
        );
1023
1024
        $form->setElement(
1025
            'select',
1026
            'cancelStatusId',
1027
            array(
1028
                'label' => 'Zahlungsstatus nach der Stornierung',
1029
                'value' => 17,
1030
                'store' => 'base.PaymentStatus',
1031
                'displayField' => 'description',
1032
                'valueField' => 'id',
1033
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
1034
                'position' => 29
1035
            )
1036
        );
1037
        
1038
        $form->setElement(
1039
            'select',
1040
            'klarnaLogLevel',
1041
            array(
1042
                'label' => 'Detaillevel der Logeinträge zur Fehlerverfolgung',
1043
                'value' => 0,
1044
                'store' => array(
1045
                    array(0, 'Nichts protokollieren'),
1046
                    array(1, 'Nur Fehler protokollieren'),
1047
                    array(2, 'Fehler und Warnungen protokollieren'),
1048
                    array(3, 'Alle Meldungen protokollieren'),
1049
                    array(4, 'Alle Meldungen und zusätzlich Entwicklerinformationen protokollieren (Große Logdateien!)'),
1050
                ),
1051
                'scope' => \Shopware\Models\Config\Element::SCOPE_SHOP,
1052
                'helpText' => 'Diese Einstellmöglichkeit dient vor allem der Nachverfolgung von Fehlern im Ablauf. Die Logdatei finden Sie unter var/log/klarnaTrace.log ihrer Shopware-Installation.',
1053
                'position' => 30
1054
            )
1055
        );
1056
    }
1057
1058
    /**
1059
     *
1060
     */
1061
    public function createMyTranslations()
1062
    {
1063
        $form = $this->Form();
1064
        $translations = $this->getTranslationArray();
1065
1066
        // In 4.2.2 we introduced a helper function for this, so we can skip the custom logic
1067
        if ($this->assertMinimumVersion('4.2.2')) {
1068
            $this->addFormTranslations($translations);
1069
            return true;
1070
        }
1071
1072
        $shopRepository = Shopware()->Models()->getRepository('\Shopware\Models\Shop\Locale');
1073
        foreach ($translations as $locale => $snippets) {
1074
            /** @var \Shopware\Models\Shop\Locale|null $localeModel */
1075
            $localeModel = $shopRepository->findOneBy(array('locale' => $locale));
1076
            if ($localeModel === null) {
1077
                continue;
1078
            }
1079
            foreach ($snippets as $element => $snippet) {
1080
                $translationModel = null;
1081
                //get the form element by name
1082
                $elementModel = $form->getElement($element);
1083
1084
                //not found? continue with next snippet
1085
                if ($elementModel === null) {
1086
                    continue;
1087
                }
1088
1089
                // Try to load existing translation
1090
                foreach ($elementModel->getTranslations() as $translation) {
1091
                    if ($translation->getLocale()->getLocale() == $locale) {
1092
                        $translationModel = $translation;
1093
                        break;
1094
                    }
1095
                }
1096
1097
                // If none found create a new one
1098
                if (!$translationModel) {
1099
                    $translationModel = new \Shopware\Models\Config\ElementTranslation();
1100
                    $translationModel->setLocale($localeModel);
1101
                    //add the translation to the form element
1102
                    $elementModel->addTranslation($translationModel);
1103
                }
1104
1105
                if ($snippet['label']) {
1106
                    $translationModel->setLabel($snippet['label']);
1107
                }
1108
1109
                if ($snippet['description']) {
1110
                    $translationModel->setDescription($snippet['description']);
1111
                }
1112
            }
1113
        }
1114
    }
1115
1116
    /**
1117
     *
1118
     */
1119
    public function createMyAttributes()
1120
    {
1121
        try {
1122
            $this->get('models')->addAttribute(
1123
                's_order_details_attributes',
1124
                'swag_klarna',
1125
                'invoice_number',
1126
                'VARCHAR(255)'
1127
            );
1128
        } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
1129
        }
1130
1131
        $this->get('models')->generateAttributeModels(
1132
            array(
1133
                's_order_details_attributes'
1134
            )
1135
        );
1136
1137
        try {
1138
            $this->get('models')->addAttribute(
1139
                's_order_attributes',
1140
                'swag_klarna',
1141
                'status',
1142
                'VARCHAR(255)'
1143
            );
1144
            $this->get('models')->addAttribute(
1145
                's_order_attributes',
1146
                'swag_klarna',
1147
                'invoice_number',
1148
                'VARCHAR(255)'
1149
            );
1150
1151
            $this->get('models')->addAttribute(
1152
                's_core_paymentmeans_attributes',
1153
                'swag_klarna',
1154
                'show_in_klarna_iframe',
1155
                'int(11)'
1156
            );
1157
            $this->get('models')->addAttribute(
1158
                's_core_paymentmeans_attributes',
1159
                'swag_klarna',
1160
                'allow_in_payment_container',
1161
                'int(11)'
1162
            );
1163
            $this->get('models')->addAttribute(
1164
                's_core_paymentmeans_attributes',
1165
                'swag_klarna',
1166
                'klarna_media',
1167
                'VARCHAR(255)'
1168
            );
1169
        } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
1170
        }
1171
1172
        $this->get('models')->generateAttributeModels(
1173
            array(
1174
                's_order_attributes',
1175
                's_core_paymentmeans_attributes'
1176
            )
1177
        );
1178
        
1179
        if ($this->assertMinimumVersion('5.2')) {
1180
            $this->get('shopware_attribute.crud_service')->update(
1181
                's_core_paymentmeans_attributes',
1182
                'swag_klarna_show_in_klarna_iframe',
1183
                'boolean',
1184
                [
1185
                    'label' => 'In Klarna Checkout einbinden',
1186
                    'helpText' => 'Bindet die Zahlungsart direkt in das Klarna iFrame ein',
1187
                    'displayInBackend' => true,
1188
                    'pluginId' => $this->getId()
1189
                ]
1190
            );
1191
            $this->get('shopware_attribute.crud_service')->update(
1192
                's_core_paymentmeans_attributes',
1193
                'swag_klarna_allow_in_payment_container',
1194
                'boolean',
1195
                [
1196
                    'label' => 'Nicht neben dem Klarna Checkout anzeigen',
1197
                    'helpText' => 'Versteckt die Zahlungsart in dem "Andere Zahlungsarten-Container" im Klarna Checkout',
1198
                    'displayInBackend' => true,
1199
                    'pluginId' => $this->getId()
1200
                ]
1201
            );    
1202
            $this->get('shopware_attribute.crud_service')->update(
1203
                's_core_paymentmeans_attributes',
1204
                'swag_klarna_klarna_media',
1205
                'string',
1206
                [
1207
                    'label' => 'Bild Name für Klarna Checkout',
1208
                    'helpText' => 'Zeigt die Zahlungsart zusätzlich mit einem Bild im iFrame an. Funktioniert nur, wenn SSL konfiguriert ist. Optimale Größe: 276x48px.'
1209
                    . 'Das Bild muss im Order /media/image gespeichert werden',
1210
                    'displayInBackend' => true,
1211
                    'pluginId' => $this->getId()
1212
                ]
1213
            );             
1214
            
1215
        }        
1216
    }
1217
1218
    public function registerMyTemplateDir($isBackend = false)
1219
    {
1220
        if ($isBackend) {
1221
            $this->get('template')->addTemplateDir(__DIR__ . '/Views/', 'klarna');
1222
        } elseif ($this->isTemplateResponsive()) {
1223
            $this->get('template')->addTemplateDir(__DIR__ . '/Views/responsive', 'klarna');
1224
        } else {
1225
            $this->get('template')->addTemplateDir(__DIR__ . '/Views/_emotion', 'klarna');
1226
        }
1227
    }
1228
1229
    /**
1230
     * Checks if the the current Template is responsive
1231
     *
1232
     * @return bool
1233
     */
1234
    public function isTemplateResponsive()
1235
    {
1236
        $template = $this->Application()->Shop()->getTemplate()->getVersion();
1237
        if ($template < 3) {
1238
            return false;
1239
        }
1240
1241
        return true;
1242
    }
1243
1244
    /**
1245
     * Returns the path to a frontend controller for an event.
1246
     *
1247
     * @return string
1248
     */
1249
    public function onGetControllerPathFrontend()
1250
    {
1251
        $this->registerMyTemplateDir();
1252
1253
        return __DIR__ . '/Controllers/Frontend/PaymentKlarna.php';
1254
    }
1255
1256
    /**
1257
     * Returns the path to a backend controller for an event.
1258
     *
1259
     * @return string
1260
     */
1261
    public function onGetControllerPathBackend()
1262
    {
1263
        $this->registerMyTemplateDir(true);
1264
        $this->Application()->Snippets()->addConfigDir(
1265
            __DIR__ . '/Snippets/'
1266
        );
1267
1268
        return __DIR__ . '/Controllers/Backend/PaymentKlarna.php';
1269
    }
1270
1271
    /**
1272
     * @param Enlight_Event_EventArgs $args
1273
     */
1274
    public function onPostDispatch(Enlight_Event_EventArgs $args)
1275
    {
1276
        /** @var $action Enlight_Controller_Action */
1277
        $action = $args->getSubject();
1278
        $request = $action->Request();
1279
        $response = $action->Response();
1280
        $view = $action->View();
1281
1282
        if (!$request->isDispatched()
1283
            || $response->isException()
1284
            || $request->getModuleName() != 'frontend'
1285
            || !$view->hasTemplate()
1286
        ) {
1287
            return;
1288
        }
1289
1290
        // just return in case kco payment is deactivated in backend
1291
1292
        if (!$this->isKcoPaymentActive()){
1293
            return;
1294
        }
1295
        $user = $view->getAssign('sUserData');
1296
        $config = $this->Config();
1297
1298
        // this is used for showing klarna buttons in basket
1299
        if ($request->getControllerName() == 'checkout'
1300
            && ($request->getActionName() == 'cart' || $request->getActionName() == 'ajaxCart')
1301
        ) {
1302
            $this->registerMyTemplateDir();
1303
            $view->assign('KlarnaEnableButton', (bool)$config->get('showKlarnaButton'));
1304
            $view->assign('KlarnaShowCheckoutButton', $this->getShowCheckoutButton($user));
1305
            $view->assign('klarnaKcoPaymentActive', $this->isKlarnaKcoPaymentActive($user));
1306
            $view->assign('KlarnaPaymentDescription', $this->getPayment()->getDescription());
1307
            if (!$this->isTemplateResponsive()) {
1308
                $view->extendsTemplate('frontend/payment_klarna_checkout/cart.tpl');
1309
            }
1310
        }
1311
1312
        // show klarna invoice information on article detail pages
1313
        if (!empty($config->partPaymentWidget)
1314
            && $request->getControllerName() == 'detail' && $request->getActionName() == 'index'
1315
        ) {
1316
            $this->registerMyTemplateDir();
1317
            //Do not shot the logo on the detail page if the kpm-plugin is active
1318
            $view->KlarnaShowLogo = !$this->isKpmActive();
1319
            $view->KlarnaLocale = $this->getLocale();
1320
            $view->KlarnaMerchantId = $config->get('merchantId');
1321
            if (!$this->isTemplateResponsive()) {
1322
                $view->extendsTemplate('frontend/payment_klarna_part/detail.tpl');
1323
            }
1324
        }
1325
1326
        if ($request->getControllerName() == 'register' && $request->getActionName() == 'index') {
1327
            $this->registerMyTemplateDir();
1328
            $view->assign('KlarnaLocale', $this->getLocale());
1329
            $view->assign('KlarnaMerchantId', $config->get('merchantId'));
1330
            $view->assign('KlarnaHideCheckoutSteps', true);
1331
            
1332
            if (version_compare(Shopware::VERSION, '5.2.0', '<')){
1333
                $view->assign('KlarnaSkipLoginFix', true);
1334
            }
1335
            if (!$this->isTemplateResponsive()) {
1336
                $view->extendsTemplate('frontend/payment_klarna_checkout/register.tpl');
1337
            }
1338
            
1339
        }
1340
1341
        if ($request->getControllerName() == 'account' && $request->getActionName() == 'ajax_login') {
1342
            $this->registerMyTemplateDir();
1343
            $view->assign('KlarnaLocale', $this->getLocale());
1344
            $view->assign('KlarnaMerchantId', $config->get('merchantId'));
1345
            
1346
            if (!$this->isTemplateResponsive()) {
1347
                $view->extendsTemplate('frontend/payment_klarna_checkout/ajax_login.tpl');
1348
            }
1349
        }
1350
1351
    }
1352
1353
    /**
1354
     * Populate register form with saved data on changing klarna and register tabs
1355
     *
1356
     * @param Enlight_Event_EventArgs $args
1357
     */
1358
    public function onPostDispatchFrontendRegister($args)
1359
    {
1360
        /** @var $action Enlight_Controller_Action */
1361
        $action = $args->getSubject();
1362
        $view = $action->View();
1363
        $request = $action->Request();
1364
        /** @var Enlight_Components_Session_Namespace $session */
1365
        $session = $this->Application()->Session();
1366
1367
         // Switch User to external PaymentId after registration
1368
         if (isset($session['KlarnaExternalPaymentId'])) {
1369
                $this->savePayment($session['KlarnaExternalPaymentId']);
1370
        }
1371
1372
       $view->assign('klarnaRedirect', $request->has('klarnaRedirect') && $request->getParam('klarnaRedirect') == 1);
1373
    }
1374
    
1375
1376
    /**
1377
     * Helper method to set the selected payment-method into the session to change it in the customer-account after logging in
1378
     *
1379
     * @param $paymentId
1380
     * @throws Enlight_Exception
1381
     */
1382
    public function savePayment($paymentId)
1383
    {
1384
        $admin = Shopware()->Modules()->Admin();
1385
        $admin->sSYSTEM->_POST['sPayment'] = $paymentId;
1386
        $admin->sUpdatePayment($paymentId);
1387
1388
    }
1389
1390
    public function addJsFiles()
1391
    {
1392
        $jsPath = array(
1393
            __DIR__ . '/Views/responsive/frontend/_public/src/js/jquery.klarna_checkout.js'
1394
        );
1395
1396
        return new Doctrine\Common\Collections\ArrayCollection($jsPath);
1397
    }
1398
1399
    /**
1400
     * @param Enlight_Event_EventArgs $args
1401
     */
1402 View Code Duplication
    public function onLoadOrderBackendModule(Enlight_Event_EventArgs $args)
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...
1403
    {
1404
        /** @var $subject Enlight_Controller_Action */
1405
        $subject = $args->getSubject();
1406
        $request = $subject->Request();
1407
        $view = $subject->View();
1408
1409
        switch ($request->getActionName()) {
1410
            case 'load':
1411
                $this->registerMyTemplateDir(true);
1412
                $view->extendsTemplate('backend/order/payment_klarna.js');
1413
                break;
1414
            default:
1415
                break;
1416
        }
1417
    }
1418
1419
    /**
1420
     * @param Enlight_Event_EventArgs $args
1421
     */
1422 View Code Duplication
    public function onLoadPaymentBackendModule(Enlight_Event_EventArgs $args)
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...
1423
    {
1424
        /** @var $subject Enlight_Controller_Action */
1425
        $subject = $args->getSubject();
1426
        $request = $subject->Request();
1427
        $view = $subject->View();
1428
1429
        switch ($request->getActionName()) {
1430
            case 'load':
1431
                $this->registerMyTemplateDir(true);
1432
                $view->extendsTemplate('backend/payment/payment_klarna.js');
1433
                break;
1434
            default:
1435
                break;
1436
        }
1437
    }
1438
1439
    public function updateOrderVariables()
1440
    {
1441
        $session = Shopware()->Session();
1442
        $admin = Shopware()->Modules()->Admin();
1443
        /** @var ArrayObject $orderVariables */
1444
        $orderVariables = $session['sOrderVariables'];
1445
        $userData = $admin->sGetUserData();
1446
        $userData['payment'] = $orderVariables['sUserData']['payment'];
1447
        $userData['additional'] = array_merge(
1448
            $orderVariables['sUserData']['additional'],
1449
            $userData['additional']
1450
        );
1451
        
1452
        if (isset($session['sChangedCountry'])){
1453
            
1454
            /** @var \Shopware\Components\Model\ModelManager $em */
1455
            $em = $this->get('models');
1456
1457
            /** @var \Shopware\Models\Customer\Customer $customer */
1458
            $country = $em->getRepository('Shopware\Models\Country\Country')->findOneBy(array('id' => $session['sChangedCountry']));            
1459
            $userData['shippingaddress']['country'] =$country;     
1460
            $userData['billingaddress']['country'] =$country;   
1461
            $userData['shippingaddress']['countryID'] = $session['sChangedCountry'];
1462
            $userData['billingaddress']['countryID'] = $session['sChangedCountry'];
1463
         }
1464
        
1465
        $orderVariables['sUserData'] = $userData;
1466
        $testbreakpoint = 0;
0 ignored issues
show
Unused Code introduced by
$testbreakpoint 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...
1467
1468
    }
1469
1470
    /**
1471
     * @param $shop Shopware\Models\Shop\Shop
1472
     * @return int|null
1473
     */
1474 View Code Duplication
    public function getCountryByShop($shop)
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...
1475
    {
1476
        $locale = $shop->getLocale()->getLocale();
1477
        $this->klarnaLog("Entering Bootstrap::getCountryByShop", 3);
1478
        $locale = explode('_', $locale);
1479
        $locale = isset($locale[1]) ? $locale[1] : $locale[0];
1480
        $this->klarnaLog("Bootstrap::getCountryByShop locale to request for:".$locale,3);
1481
        $sql = 'SELECT id FROM s_core_countries WHERE countryiso=?';
1482
        $countryId = Shopware()->Db()->fetchOne($sql, array($locale));
1483
        $countryId = ($countryId) ? (int)$countryId : null;
1484
                
1485
        return $countryId;
1486
    }
1487
1488
    /**
1489
     * Get user country by country id
1490
     *
1491
     * @param $id
1492
     * @return string
1493
     */
1494
    public function getCountryIsoById($id)
1495
    {
1496
        $sql = 'SELECT countryiso FROM s_core_countries WHERE id = ?';
1497
        $countryIso = Shopware()->Db()->fetchOne($sql, array($id));
1498
1499
        return $countryIso;
1500
    }
1501
1502
    public function getLocale($underscore = false, $countryIso = null)
1503
    {
1504
        /** @var \Shopware\Models\Shop\Shop $shop */
1505
        $shop = $this->Application()->Shop();
1506
        $locale = $shop->getLocale()->getLocale();
1507
        $locale = strtolower($locale);
1508
        if (!$underscore) {
1509
            $locale = str_replace('_', '-', $locale);
1510
        }
1511
        $locale = $locale == 'nn-no' ? 'nb-no' : $locale;
1512
1513
        if ($locale == 'de-de') {
1514
            if($countryIso == 'CH') {
1515
                $locale = 'de-ch';
1516
            } elseif ($countryIso == 'AT') {
1517
                $locale = 'de-at';
1518
            }
1519
        }
1520
1521
        return $locale;
1522
    }
1523
1524
    public function getCheckoutOptions($allowPackstation = true, $dispatch = array())
1525
    {
1526
        $config = $this->Config();
1527
        $options = $this->getColorConfigOptions($config);
1528
1529
        $options['allow_separate_shipping_address'] = (bool)$config->get('allowSeparateShippingAddress');
1530
        $options['packstation_enabled'] = (bool)$config->get('supportPackstation') && $allowPackstation;
1531
        $options['phone_mandatory'] = (bool)$config->get('mandatoryPhone');
1532
        $options['date_of_birth_mandatory'] = (bool)$config->get('mandatoryBirthday');
1533
1534
        if (!empty($dispatch)) {
1535
            $options['shipping_details'] = $dispatch['description'];
1536
        }
1537
1538
        return $options;
1539
    }
1540
1541
    public function getCheckoutCart($basket)
1542
    {
1543
        $cart = array();
1544
        foreach ($basket['content'] as $index=>$basketItem) {
1545
            // compatibility to shopware plugin custom products
1546
            if (isset($basketItem['custom_product_prices'])) {
1547
                $basketItemPrice = (double)$basketItem['custom_product_prices']['total'];
1548
            }
1549
            else {
1550
                $basketItemPrice = (double)str_replace(',', '.', $basketItem['price']);
1551
            }
1552
            $unitPrice = round($basketItemPrice * 100);
1553
            $cart[] = array(
1554
                'type' => $unitPrice >= 0 ? 'physical' : 'discount',
1555
                'reference' => $basketItem['ordernumber'],
1556
                'name' => $basketItem['articlename'],
1557
                'quantity' => (int)$basketItem['quantity'],
1558
                'unit_price' => (int)$unitPrice,
1559
                'tax_rate' => (int)round($basketItem['tax_rate'] * 100)
1560
            );
1561
        }
1562
        if (!empty($basket['sShippingcosts'])) {
1563
            $shippingCostsWithTax = $basket['sShippingcostsWithTax'];
1564
            $shippingAmount = !empty($shippingCostsWithTax) ? $shippingCostsWithTax : $basket['sShippingcosts'];
1565
            $cart[] = array(
1566
                'type' => 'shipping_fee',
1567
                'reference' => 'SHIPPING',
1568
                'name' => 'Shipping Fee',
1569
                'quantity' => 1,
1570
                'unit_price' => (int)round($shippingAmount * 100),
1571
                'tax_rate' => (int)round($basket['sShippingcostsTax'] * 100),
1572
            );
1573
        }
1574
1575
        return $cart;
1576
    }
1577
1578
    public function getCheckoutMerchant()
1579
    {
1580
        /** @var \Shopware\Components\Routing\RouterInterface $router */
1581
        $router = $this->Application()->Front()->Router();
1582
        $merchant = array();
1583
        $merchant['id'] = $this->Config()->get('merchantId');
1584
        $merchant['terms_uri'] = $router->assemble(
1585
            array(
1586
                'controller' => 'custom',
1587
                'sCustom' => $this->Config()->get('termSiteId', 4),
1588
                'forceSecure' => true
1589
            )
1590
        );
1591
        $merchant['checkout_uri'] = $router->assemble(
1592
            array(
1593
                'action' => 'confirm'
1594
            )
1595
        );
1596
        $merchant['confirmation_uri'] = $router->assemble(
1597
            array(
1598
                'controller' => 'payment_klarna',
1599
                'action' => 'return',
1600
                'forceSecure' => true
1601
            )
1602
        ) . "?transactionId={checkout.order.uri}";
1603
        $merchant['push_uri'] = $router->assemble(
1604
            array(
1605
                'controller' => 'payment_klarna',
1606
                'action' => 'push',
1607
                'forceSecure' => true,
1608
                'appendSession' => true
1609
            )
1610
        ) . "&transactionId={checkout.order.uri}";
1611
        $merchant['back_to_store_uri'] = $router->assemble(
1612
            array(
1613
                'controller' => 'index',
1614
                'action' => 'index'
1615
            )
1616
        );
1617
1618
        return $merchant;
1619
    }
1620
1621
    public function getCheckoutAddress($user, $type = 'billing')
1622
    {
1623
        if (empty($user[$type . 'address']['zipcode']) || $user[$type . 'address']['zipcode'] == '00000') {
1624
            return array();
1625
        }
1626
1627
        $address = array(
1628
            'given_name' => $user[$type . 'address']['firstname'],
1629
            'family_name' => $user[$type . 'address']['lastname'],
1630
            'postal_code' => $user[$type . 'address']['zipcode'],
1631
            'city' => $user[$type . 'address']['city'],
1632
            'country' => $user['additional'][$type == 'billing' ? 'country' : 'countryShipping']['countryiso'],
1633
            'email' => $user['additional']['user']['email'],
1634
            'phone' => $user['billingaddress']['phone'],
1635
        );
1636
        $address['country'] = strtolower($address['country']);
1637
        if ($address['country'] == 'de' || $address['country'] == 'nl') {
1638
            $address['title'] = $user[$type . 'address']['salutation'] == 'ms' ? 'Frau' : 'Herr';
1639
            if ($this->assertMinimumVersion('5.0.0')) {
1640
                /** @var StreetSplitService $streetSplitService */
1641
                $streetSplitService = Shopware()->StreetSplitService();
1642
                $streetAndNumber = $streetSplitService->split($user[$type . 'address']['street']);
1643
1644
                $address['street_name'] = $streetAndNumber['streetName'];
1645
                $address['street_number'] = $streetAndNumber['streetNumber'];
1646 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...
1647
                $address['street_name'] = $user[$type . 'address']['street'];
1648
                $address['street_number'] = $user[$type . 'address']['streetnumber'];
1649
            }
1650 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...
1651
            $address['street_address'] = trim(
1652
                $user[$type . 'address']['street'] . ' ' . $user[$type . 'address']['streetnumber']
1653
            );
1654
        }
1655
1656
        // Make sure phone number is unset if empty
1657
        if ($address['phone'] === null){
1658
            unset($address['phone']);
1659
        }
1660
        return $address;
1661
    }
1662
1663
    public function getCheckoutCustomer($user)
1664
    {
1665
        $customer = array(
1666
            'type' => 'person'
1667
        );
1668
        if (!empty($user['billingaddress']['birthday']) && $user['billingaddress']['birthday'] != '0000-00-00') {
1669
            $customer['date_of_birth'] = $user['billingaddress']['birthday'];
1670
        }
1671
        // SW 5.2 and newer
1672
        if (!empty($user['additional']['user']['birthday']) && $user['additional']['user'] != '0000-00-00') {
1673
            $customer['date_of_birth'] = $user['additional']['user']['birthday'];
1674
        }
1675
1676
        return $customer;
1677
    }
1678
1679
    /**
1680
     *
1681
     * @return array
1682
     */
1683
    public function getLabel()
1684
    {
1685
        return 'Klarna Checkout';
1686
    }
1687
1688
    /**
1689
     * @return string
1690
     * @throws Exception
1691
     */
1692
    public function getVersion()
1693
    {
1694
        $info = json_decode(file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'plugin.json'), true);
1695
1696
        if ($info) {
1697
            return $info['currentVersion'];
1698
        } else {
1699
            throw new Exception('The plugin has an invalid version file.');
1700
        }
1701
    }
1702
1703
    /**
1704
     * @return array
1705
     */
1706
    public function getInfo()
1707
    {
1708
        return array(
1709
            'version' => $this->getVersion(),
1710
            'label' => $this->getLabel(),
1711
            'description' => file_get_contents(__DIR__ . '/info.txt')
1712
        );
1713
    }
1714
1715
    /**
1716
     * Creates and returns the klarna client for an event.
1717
     *
1718
     * @return \Klarna_Checkout_Connector
1719
     */
1720
    public function onInitResourceKlarnaCheckoutConnector()
1721
    {
1722
        require_once __DIR__ . '/Components/KlarnaCheckout/Checkout.php';
1723
        if ($this->Config()->get('testDrive')) {
1724
            Klarna_Checkout_Order::$baseUri = 'https://checkout.testdrive.klarna.com/checkout/orders';
1725
        } else {
1726
            Klarna_Checkout_Order::$baseUri = 'https://checkout.klarna.com/checkout/orders';
1727
        }
1728
        Klarna_Checkout_Order::$contentType = "application/vnd.klarna.checkout.aggregated-order-v2+json";
1729
        $sharedSecret = $this->Config()->get('sharedSecret');
1730
        $connector = Klarna_Checkout_Connector::create($sharedSecret);
1731
        $this->klarnaLog("Created Klarna Connector:", 4, $connector);
1732
1733
        return $connector;
1734
    }
1735
1736
    /**
1737
     * @return Klarna
1738
     */
1739
    public function onInitResourceKlarnaService()
1740
    {
1741
        require_once __DIR__ . '/Components/Klarna/Klarna.php';
1742
        require_once __DIR__ . '/Components/Klarna/transport/xmlrpc-3.0.0.beta/lib/xmlrpc.inc';
1743
1744
        $k = new Klarna();
1745
        return $k;
1746
    }
1747
1748
    /**
1749
     * Provide the file collection for less
1750
     *
1751
     * @return \Doctrine\Common\Collections\ArrayCollection
1752
     */
1753
    public function addLessFiles()
1754
    {
1755
        $less = new \Shopware\Components\Theme\LessDefinition(
1756
            //configuration
1757
            array(),
1758
            //less files to compile
1759
            array(
1760
                __DIR__ . '/Views/responsive/frontend/_public/src/less/all.less'
1761
            ),
1762
            //import directory
1763
            __DIR__
1764
        );
1765
1766
        return new Doctrine\Common\Collections\ArrayCollection(array($less));
1767
    }
1768
1769
    /**
1770
     * @param string $requiredVersion
1771
     * @return bool|mixed
1772
     */
1773
    protected function assertMinimumVersion($requiredVersion)
1774
    {
1775
        if (Shopware::VERSION === '___VERSION___') {
1776
            return true;
1777
        }
1778
1779
        return version_compare(Shopware::VERSION, $requiredVersion, '>=');
1780
    }
1781
1782
    /**
1783
     * This event is executed when the expressAction of the checkout-controller should be executed.
1784
     * It is needed to redirect the user back to the klarna checkout after deleting an article in the klarna checkout.
1785
     *
1786
     * @param Enlight_Event_EventArgs $args
1787
     * @return bool
1788
     */
1789
    public function onCheckoutExpress(Enlight_Event_EventArgs $args)
1790
    {
1791
        /** @var $action Enlight_Controller_Action */
1792
        $action = $args->getSubject();
1793
1794
        $action->redirect(array('controller' => 'payment_klarna', 'action' => 'express'));
1795
        return true;
1796
    }
1797
1798
    /**
1799
     * Mapping to populate klarna checkout with saved information from register page
1800
     *
1801
     * @param $form
1802
     * @return mixed
1803
     */
1804
    private function klarnaMapping($form)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
1805
    {
1806
        $fields = array(
1807
            'email' => 'email',
1808
            'zipcode' => 'postal_code',
1809
            'firstname' => 'given_name',
1810
            'lastname' => 'family_name',
1811
        );
1812
1813
        $create = array();
1814
        foreach ($fields as $formField => $klarnaField) {
1815 View Code Duplication
            if (!empty($form['register']['personal'][$formField])) {
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...
1816
                $create['shipping_address'][$klarnaField] = $form['register']['personal'][$formField];
1817
            }
1818 View Code Duplication
            if (!empty($form['register']['billing'][$formField])) {
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...
1819
                $create['shipping_address'][$klarnaField] = $form['register']['billing'][$formField];
1820
            }
1821
        }
1822
1823
        $countryIso = $this->getCountryIsoById($form['register']['billing']['country']);
1824
1825
        $salutation = $form['register']['personal']['salutation'];
1826
        if (!empty($salutation) && ($countryIso == 'DE' || $countryIso == 'NL')) {
1827
            $create['shipping_address']['title'] = ($salutation == 'ms' ? 'Frau' : 'Herr');//German names
1828
        }
1829
1830
        $billingStreet = $form['register']['billing']['street'];
1831
        $billingStreetNumber = $form['register']['billing']['streetnumber'];
1832
        if (!empty($billingStreet)) {
1833
            if ($countryIso == 'DE' || $countryIso == 'NL') {
1834
                if ($this->assertMinimumVersion('5.0.0')) {
1835
                    preg_match('(^(?P<street>.+)\\s+(?P<number>\\d+\\S*)$)', $billingStreet, $matches);
1836
1837
                    $create['shipping_address']['street_name'] = $matches['street'];
1838
                    $create['shipping_address']['street_number'] = $matches['number'];
1839
                } else {
1840
                    $create['shipping_address']['street_name'] = $form['register']['billing']['street'];
1841
                    $create['shipping_address']['street_number'] = $billingStreetNumber;
1842
                }
1843
            } else {
1844
                $create['shipping_address']['street_address'] = $billingStreet . ' ' . $billingStreetNumber;
1845
            }
1846
        }
1847
1848
        return $create;
1849
    }
1850
1851
    /**
1852
     * Helper method to read the color-config options properly.
1853
     *
1854
     * @param $config Enlight_Config
1855
     * @return mixed
1856
     */
1857
    private function getColorConfigOptions($config)
1858
    {
1859
        $options = array();
1860
        $checkoutButtonColor = $config->get('checkoutButtonColor');
1861
        $checkoutButtonTextColor = $config->get('checkoutButtonTextColor');
1862
        $checkoutCheckboxColor = $config->get('checkoutCheckboxColor');
1863
        $checkoutCheckboxCheckMarkColor = $config->get('checkoutCheckboxCheckmarkColor');
1864
        $checkoutHeaderColor = $config->get('checkoutHeaderColor');
1865
        $checkoutLinkColor = $config->get('checkoutLinkColor');
1866
1867
        if (!empty($checkoutButtonColor) && $checkoutButtonColor !== "#") {
1868
            $options['color_button'] = $checkoutButtonColor;
1869
        }
1870
        if (!empty($checkoutButtonTextColor) && $checkoutButtonTextColor !== "#") {
1871
            $options['color_button_text'] = $checkoutButtonTextColor;
1872
        }
1873
        if (!empty($checkoutCheckboxColor) && $checkoutCheckboxColor !== "#") {
1874
            $options['color_checkbox'] = $checkoutCheckboxColor;
1875
        }
1876
        if (!empty($checkoutCheckboxCheckMarkColor) && $checkoutCheckboxCheckMarkColor !== "#") {
1877
            $options['color_checkbox_checkmark'] = $checkoutCheckboxCheckMarkColor;
1878
        }
1879
        if (!empty($checkoutHeaderColor) && $checkoutHeaderColor !== "#") {
1880
            $options['color_header'] = $checkoutHeaderColor;
1881
        }
1882
        if (!empty($checkoutLinkColor) && $checkoutLinkColor !== "#") {
1883
            $options['color_link'] = $checkoutLinkColor;
1884
        }
1885
1886
        return $options;
1887
    }
1888
1889
    /**
1890
     * @param $view Enlight_View_Default
1891
     * @param $config Enlight_Config
1892
     */
1893
    public function getViewConfig($view, $config)
1894
    {
1895
        /** @var sAdmin $adminModule */
1896
        $adminModule = $this->get('modules')->Admin();
1897
        $session = $this->get('session');
1898
        $sCountry = $session['sCountry'];
0 ignored issues
show
Unused Code introduced by
$sCountry 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...
1899
        $view->assign('sCountryId', $session['sCountry']);
1900
        $view->assign('sPayments', $this->filterPayments($adminModule->sGetPaymentMeans()));
1901
        $view->assign('sCountryList', $adminModule->sGetCountryList());
1902
        $view->assign('KlarnaHideCheckoutSteps', true);
1903
        $view->assign('KlarnaShowB2bSelect', (bool)$config->get('showB2bSelect'));
1904
        $view->assign('KlarnaShowBasket', (bool)$config->get('showMiniBasket'));
1905
        $view->assign('KlarnaShowDispatch', (bool)$config->get('showDispatch'));
1906
        $view->assign(
1907
            'KlarnaCDNLink',
1908
            $this->buildCDNLink()
1909
        );
1910
        $view->assign(
1911
            'KlarnaLoggedInUser',
1912
            $view->sUserData['billingaddress']['lastname'] == 'Klarna Checkout'
1913
        );
1914
        $debugShowLogin = !empty($session->sUserId);
0 ignored issues
show
Unused Code introduced by
$debugShowLogin 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...
1915
        $debugShowLogin2 = $this->getShowLoginConfig($config,!empty($session->sUserId));
0 ignored issues
show
Unused Code introduced by
$debugShowLogin2 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...
1916
        $view->assign(
1917
            'KlarnaShowLogin',
1918
            $this->getShowLoginConfig($config, !empty($session->sUserId))
1919
        );
1920
        $view->assign(
1921
            'KlarnaDisplayType',
1922
            $this->getKlarnaDisplayType($config)
1923
        );
1924
        $view->assign(
1925
            'KlarnaPositionOrder',
1926
            $this->getPositionOrder($config)
1927
        );
1928
    }
1929
1930
    /**
1931
     * Helper method to get the config whether or not to show the login-panel in the klarna-checkout.
1932
     *
1933
     * @param $config Enlight_Config
1934
     * @param $lastName string
1935
     * @return bool
1936
     */
1937
    private function getShowLoginConfig($config, $userLoggedIn)
1938
    {
1939
        return (bool)$config->get('showLoginPanel') && !($userLoggedIn);
1940
    }
1941
1942
    /**demo
1943
     * Helper method to read all countries.
1944
     * Reads all countries connected to a locale by the iso.
1945
     * Additionally reads out if that country is configured for the klarna-payment method.
1946
     * @example array(
1947
         array(
1948
             'id' => 1,
1949
             'localeId' => 17,
1950
             'countryname' => 'Germany',
1951
             'configured' => 0
1952
         ),
1953
         array(
1954
             'id' => 4,
1955
             'localeId' => 22,
1956
             'countryname' => 'Austria',
1957
             'configured' => 1
1958
         )
1959
     );
1960
     * @return array
1961
     */
1962
    private function getAllCountries()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
1963
    {
1964
        if (empty($this->countries)) {
1965
            $sql = "SELECT cl.id, cc.id as countryId, cl.territory, cc.countryname, IF(pmc.countryID IS NULL, IF(pmc2.countryID IS NULL, 1, 0), 1) as configured
1966
                FROM s_core_countries cc
1967
                INNER JOIN s_core_locales cl
1968
                    ON cl.locale LIKE CONCAT('%_', cc.countryiso)
1969
                LEFT JOIN s_core_paymentmeans_countries pmc
1970
                    ON cc.id = pmc.countryID
1971
                    AND pmc.paymentID = (SELECT id FROM s_core_paymentmeans WHERE action='payment_klarna')
1972
                LEFT JOIN s_core_paymentmeans_countries pmc2
1973
                    ON pmc2.paymentID = (SELECT id FROM s_core_paymentmeans WHERE action='payment_klarna')
1974
                WHERE cc.active = 1
1975
                GROUP BY cc.countryname
1976
                ORDER BY cc.position, cc.countryname";
1977
1978
            $result = Shopware()->Db()->fetchAssoc($sql, array());
1979
1980
            // Load translations if available
1981
            $this->countries = array_map(function ($country) {
1982
                $country['id'] = $country['countryId'];
1983
                return Shopware()->Modules()->Admin()->sGetCountryTranslation($country);
1984
            }, $result);
1985
        }
1986
1987
        return $this->countries;
1988
    }
1989
1990
    /**
1991
     * Helper method to find the correct display-type for the frontend.
1992
     * Will return the value configured in the plugin-config, if there is at least one more payment-mean besides klarna.
1993
     * @param $config Enlight_Config
1994
     * @return int
1995
     */
1996
    private function getKlarnaDisplayType($config)
1997
    {
1998
        if (!$this->getOtherPayments()) {
1999
            return 2;
2000
        }
2001
        return $config->get('displayType');
2002
    }
2003
2004
    /**
2005
     * Helper method to find other payment-means besides klarna.
2006
     * @return bool
2007
     */
2008
    private function getOtherPayments()
2009
    {
2010
        $payments = $this->Application()->Modules()->Admin()->sGetPaymentMeans();
2011
2012
        foreach ($payments as $payment) {
2013
            if ($payment['action'] != 'payment_klarna') {
2014
                return true;
2015
            }
2016
        }
2017
2018
        return false;
2019
    }
2020
2021
    /**
2022
     * Helper method to figure out whether or not to show the extra klarna checkout button.
2023
     * @return bool
2024
     */
2025
    private function getShowCheckoutButton($user)
2026
    {
2027
        if (!empty($user['additional']['payment']['id']) && $user['additional']['payment']['id'] != $this->getPayment()->getId()) {
2028
            return true;
2029
        }
2030
2031
        return false;
2032
    }
2033
2034
    /**
2035
     * Helper method to get the correct order for the elements
2036
     *
2037
     * @param $config Enlight_Config
2038
     * @return array Array with the order of the elements
2039
     */
2040
    private function getPositionOrder($config)
2041
    {
2042
        $loginPanel = 'login_panel';
2043
        $miniBasket = 'mini_basket';
2044
        $dispatch = 'dispatch';
2045
        $payments = 'payments';
2046
        switch ($config->get('positionOrder')) {
2047
            case 1:
2048
                return array($loginPanel, $miniBasket, $dispatch, $payments);
2049
            case 2:
2050
                return array($loginPanel, $miniBasket, $payments, $dispatch);
2051
            case 3:
2052
                return array($dispatch, $payments, $loginPanel, $miniBasket);
2053
            case 4:
2054
            default:
2055
                return array($payments, $dispatch, $loginPanel, $miniBasket);
2056
        }
2057
    }
2058
2059
    /**
2060
     * Helper method to build the proper cdn-link for the image in the tabs-layout.
2061
     * @return string
2062
     */
2063
    private function buildCDNLink()
2064
    {
2065
        $validLocales = array(
2066
            'de_de',
2067
            'de_at',
2068
            'en_us',
2069
            'en_gb',
2070
            'fi_fi',
2071
            'sv_se',
2072
            'nb_no',
2073
        );
2074
        $locale = str_replace('-', '_', $this->getLocale());
2075
2076
        if (!in_array($locale, $validLocales)) {
2077
            $locale = 'en_gb';
2078
        }
2079
        return "https://cdn.klarna.com/1.0/shared/image/generic/badge/{$locale}/checkout/long-no-klarna-logo.png";
2080
    }
2081
2082
    /**
2083
     * Helper method to read the customer-data from the klarna order-object.
2084
     * @param Klarna_Checkout_Order $order
2085
     * @return array
2086
     */
2087
    private function getKlarnaCustomerData($order)
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
2088
    {
2089
        $billingAddress = $order['billing_address'];
2090
2091
        return array(
2092
            'personal' => array(
2093
                'customer_type' => 'private',
2094
                'salutation' => $billingAddress['title'],
2095
                'firstname' => $billingAddress['given_name'],
2096
                'lastname' => $billingAddress['family_name'],
2097
                'email' => $billingAddress['email'],
2098
                'birthday' => $order['customer']['date_of_birth'],
2099
                'phone' => $billingAddress['phone']
2100
            ),
2101
            'billing' => array(
2102
                'street' => $billingAddress['street_name'] . ' ' . $billingAddress['street_number'],
2103
                'zipcode' => $billingAddress['postal_code'],
2104
                'city' => $billingAddress['city']
2105
            )
2106
        );
2107
    }
2108
2109
    /**
2110
     * Returns an array with all translations
2111
     * @return array
2112
     */
2113
    private function getTranslationArray()
2114
    {
2115
        return array(
2116
            'en_GB' => array(
2117
                'testDrive' => array(
2118
                    'label' => 'Activate test-modus'
2119
                ),
2120
                'merchantId' => array(
2121
                    'label' => 'API merchant ID (EID)'
2122
                ),
2123
                'sharedSecret' => array(
2124
                    'label' => 'API-Secret (sharedsecret)'
2125
                ),
2126
                'termSiteId' => array(
2127
                    'label' => 'Shopsite including the terms and conditions'
2128
                ),
2129
                'allowSeparateShippingAddress' => array(
2130
                    'label' => 'Enable differing shipping address'
2131
                ),
2132
                'supportPackstation' => array(
2133
                    'label' => 'Support DHL-packstation',
2134
                    'helpText' => 'The differing shipping address must be enabled'
2135
                ),
2136
                'postnumberField' => array(
2137
                    'label' => 'Alternative field for the DHL-postnumber'
2138
                ),
2139
                'mandatoryPhone' => array(
2140
                    'label' => 'Phone mandatory field'
2141
                ),
2142
                'mandatoryBirthday' => array(
2143
                    'label' => 'Birthday mandatory field'
2144
                ),
2145
                'disableAutofocus' => array(
2146
                    'label' => 'Disable auto-focus'
2147
                ),
2148
                'showKlarnaButton' => array(
2149
                    'label' => 'Show klarna-checkout button'
2150
                ),
2151
                'checkoutButtonColor' => array(
2152
                    'label' => 'Checkout Button Color'
2153
                ),
2154
                'checkoutButtonTextColor' => array(
2155
                    'label' => 'Checkout Buttontext Color'
2156
                ),
2157
                'checkoutCheckboxColor' => array(
2158
                    'label' => 'Checkout Checkbox Color'
2159
                ),
2160
                'checkoutCheckboxCheckmarkColor' => array(
2161
                    'label' => 'Checkout Checkbox Tick Color'
2162
                ),
2163
                'checkoutHeaderColor' => array(
2164
                    'label' => 'Checkout Header Color'
2165
                ),
2166
                'checkoutLinkColor' => array(
2167
                    'label' => 'Checkout Link Color'
2168
                ),
2169
                'KlarnaExternalPayments' => array(
2170
                    'label' => 'Display external payment-methods in klarna checkout',
2171
                    'helpText' => 'Your klarna-account has to be unlocked for this feature',
2172
                ),
2173
                'displayType' => array(
2174
                    'label' => 'Klarna Checkout display-type',
2175
                    'store' => array(
2176
                        array(1, 'Display tabs'),
2177
                        array(2, 'Display only klarna checkout'),
2178
                        array(3, 'One-page display')
2179
                    ),
2180
                ),
2181
                'showB2bSelect' => array(
2182
                    'label' => 'Show B2B-select',
2183
                    'helpText' => 'Displays a new select-box containing "Private customer" and "Company" in the klarna checkout'
2184
                ),
2185
                'showLoginPanel' => array(
2186
                    'label' => 'Show login-panel',
2187
                    'helpText' => 'Displays a login-panel in the klarna-checkout',
2188
                ),
2189
                'showMiniBasket' => array(
2190
                    'label' => 'Show mini-basket',
2191
                    'helpText' => 'Displays a small overview of the basket in the klarna-checkout',
2192
                ),
2193
                'showDispatch' => array(
2194
                    'label' => 'Show shipping-country and -method',
2195
                    'helpText' => 'Shows a shipping-country and shipping-method select in the klarna-checkout'
2196
                ),
2197
                'partPaymentWidget' => array(
2198
                    'label' => 'Show partial-payment-widget on detail-page'
2199
                ),
2200
                'convertShippingFee' => array(
2201
                    'label' => 'Convert shipping-costs to an order-position'
2202
                ),
2203
                'statusId' => array(
2204
                    'label' => 'Payment status after order'
2205
                ),
2206
                'activateStatusId' => array(
2207
                    'label' => 'Payment status after activation'
2208
                ),
2209
                'cancelStatusId' => array(
2210
                    'label' => 'Payment status after cancellation'
2211
                )
2212
            )
2213
        );
2214
    }
2215
2216
    /**
2217
     * Helper method to update the klarna-payment when updating from any version to >= 2.0 of klarna.
2218
     * It adds "austria" to the valid countries.
2219
     */
2220
    private function updatePayment()
2221
    {
2222
        /** @var \Shopware\Components\Model\ModelManager $manager */
2223
        $manager = $this->get('models');
2224
        $payment = $manager->getRepository('Shopware\Models\Payment\Payment')->findOneBy(array(
2225
            'name' => 'klarna_checkout'
2226
        ));
2227
2228
        if (empty($payment)) {
2229
            return;
2230
        }
2231
2232
        $updateNeeded = true;
2233
        $countries = $payment->getCountries();
2234
        /** @var Shopware\Models\Country\Country $country */
2235
        foreach ($countries as $country) {
2236
            if ($country->getIso() == 'AT') {
2237
                $updateNeeded = false;
2238
            }
2239
        }
2240
2241
        if ($updateNeeded) {
2242
            $countries->add($manager->getRepository('Shopware\Models\Country\Country')->findOneBy(array('iso' => 'AT')));
2243
            $payment->setCountries($countries);
2244
2245
            $manager->persist($payment);
2246
            $manager->flush();
2247
        }
2248
    }
2249
2250
    /**
2251
     * Method checks if selected country is valid for use with klarna
2252
     * 
2253
     * @param string $countryId
2254
     * @return boolean
2255
     */
2256
    public function checkValidKlarnaCountry($countryId)
2257
    {
2258
        /*       $countries = $this->getPayment()->getCountries();
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
2259
               foreach ($countries as $country) {
2260
                   $allowedCountries[] = $country->getId();
2261
               }
2262
2263
               return in_array($countryId, $allowedCountries);
2264
       */
2265
        $allowedCountry = $this->getCountryByShop(Shopware()->Shop());
2266
        if ($allowedCountry == "2" && $countryId == "23") {
2267
            return true;
2268
        } elseif ($allowedCountry == "23" && $countryId == "2") {
2269
            return true;
2270
        } else {
2271
            return ($countryId == $allowedCountry);
2272
        }
2273
    }
2274
    
2275
2276
    /**
2277
     * Helper method to read all payments, that should be displayed in the klarna checkout.
2278
     * @param $basket
2279
     * @return array
2280
     */
2281
    public function getExternalPaymentMethods($basket)
2282
    {
2283
        $payments = Shopware()->Models()->getRepository('Shopware\Models\Attribute\Payment')->findBy(array(
2284
            'swagKlarnaShowInKlarnaIframe' => 1,
2285
            'swagKlarnaAllowInPaymentContainer' => 0
2286
        ));
2287
2288
        $externalPayments = array();
2289
        $externalCheckouts = array();
2290
        /** @var Shopware\Models\Attribute\Payment $payment */
2291
        foreach ($payments as $payment) {
2292
            $paymentObj = $payment->getPayment();
2293
            if (is_null($paymentObj)){
2294
                $paymentName = false;
2295
            } else {
2296
                $paymentName = $paymentObj->getName();
2297
            }
2298
            
2299
            if(!$paymentName){
2300
                continue;
2301
            }            
2302
            
2303
            if ($paymentName && $paymentName == 'klarna_checkout') {
2304
                continue;
2305
            }
2306
            $paymentArray = array(
2307
                'name' => $payment->getPayment()->getDescription(),
2308
                'redirect_uri' => $this->getRedirectUri() . '/paymentId/' . $payment->getPaymentId()
2309
            );
2310
2311
            if ($fee = $this->getFee($payment->getPayment(), $basket)) {
2312
                $paymentArray['fee'] = $fee;
2313
            }
2314
2315
            if ($description = $payment->getPayment()->getAdditionalDescription()) {
2316
                //Shorten the description to max. 500 characters
2317
                $description = strip_tags($description);
2318
                $description = preg_replace('#<!--.*-->#ms', '', $description);
2319
                $paymentArray['description'] = substr($description, 0, 497) . '...';
2320
            }
2321
2322
            //Only add to external checkouts if an image is set and if the shop supports SSL
2323
            if (Shopware()->Shop()->getSecure() && $image = $this->getImageForKlarna($payment)) {
2324
                $paymentArray['image_uri'] = $image;
2325
                $externalCheckouts[] = $paymentArray;
2326
            }
2327
2328
            $externalPayments[] = $paymentArray;
2329
        }
2330
2331
        return array($externalPayments, $externalCheckouts);
2332
    }
2333
2334
    /**
2335
     * @param Shopware\Models\Payment\Payment $payment
2336
     * @param $basket
2337
     * @return bool
2338
     */
2339
    private function getFee($payment, $basket)
2340
    {
2341
        $fee = 0;
2342
        $amount = str_replace(',', '.', $basket['Amount']);
2343
2344
        if ($surcharge = $payment->getSurcharge()) {
2345
            $fee += $surcharge;
2346
            $amount += $surcharge;
2347
        }
2348
2349
        if ($percent = $payment->getDebitPercent()) {
2350
            $fee += round($amount / 100 * $percent, 3);
2351
        }
2352
2353
        return round($fee * 100);
2354
    }
2355
2356
    /**
2357
     * Helper method to get the redirect-uri
2358
     * @return string
2359
     */
2360
    private function getRedirectUri()
2361
    {
2362
        return Shopware()->Front()->Router()->assemble(array(
2363
            'controller' => 'PaymentKlarna',
2364
            'action' => 'setPayment'
2365
        ));
2366
    }
2367
2368
    /**
2369
     * Helper method to read the image for the klarna-checkout if set
2370
     * @param Shopware\Models\Attribute\Payment $payment
2371
     * @return null|string
2372
     */
2373
    private function getImageForKlarna($payment)
2374
    {
2375
        $media = $payment->getSwagKlarnaKlarnaMedia();
2376
        if (!$payment->getSwagKlarnaShowInKlarnaIframe() || !empty($media)) {
2377
            if ($this->assertMinimumVersion('5.1') && version_compare(Shopware::VERSION, '5.2.0', '<=') ) {
2378
                $media = $this->get('shopware_media.media_service')->getUrl($media);
2379
            } else {
2380
                /** @var Enlight_Controller_Front $front */
2381
                $front = $this->get('front');
2382
                $request = $front->Request();
2383
                if ($request && $request->getHttpHost()) {
2384
                    $url = ($request->isSecure() ? 'https' : 'http') . '://' . $request->getHttpHost() . $request->getBasePath() . "/";
2385
                } else {
2386
                    $url = $front->Router()->assemble(array('controller' => 'index', 'module' => 'frontend'));
2387
                }
2388
		if (version_compare(Shopware::VERSION, '5.2.0', '>=')) {
2389
            # make sure me get only the image name, path is set in case of upgarde from SW.5.1 to 5.2
2390
            $parts = explode('/', $media);
2391
            $end = end($parts);
2392
			$media = $url . 'media/image/' . $end;
2393
		} else {
2394
	                $media = $url . $media;
2395
		}
2396
            }
2397
2398
            return $media;
2399
        }
2400
        return null;
2401
    }
2402
2403
    /**
2404
     * Helper method to filter the available payment-means.
2405
     * @param $sGetPaymentMeans
2406
     * @return array
2407
     */
2408
    private function filterPayments($sGetPaymentMeans)
2409
    {
2410
        $paymentArray = array();
2411
        foreach ($sGetPaymentMeans as $paymentMean) {
2412
            if (!$this->isPaymentAllowed($paymentMean)) {
2413
                continue;
2414
            }
2415
2416
            $paymentArray[] = $paymentMean;
2417
        }
2418
        return $paymentArray;
2419
    }
2420
2421
    /**
2422
     * Helper method to check if a payment is allowed to be
2423
     * @param $payment
2424
     * @return bool
2425
     */
2426
    private function isPaymentAllowed($payment)
2427
    {
2428
        if ($payment['name'] == 'klarna_checkout') {
2429
            return false;
2430
        }
2431
        $connection = Shopware()->Models()->getConnection();
2432
2433
        $builder = $connection->createQueryBuilder();
2434
        $builder->select('swag_klarna_allow_in_payment_container', 'swag_klarna_show_in_klarna_iframe')
2435
            ->from('s_core_paymentmeans_attributes')
2436
            ->where('paymentmeanID = :id')
2437
            ->setParameter(':id', $payment['id']);
2438
2439
        $result = reset($builder->execute()->fetchAll());
0 ignored issues
show
Bug introduced by
$builder->execute()->fetchAll() cannot be passed to reset() as the parameter $array expects a reference.
Loading history...
2440
        return !$result['swag_klarna_allow_in_payment_container'] && !$result['swag_klarna_show_in_klarna_iframe'];
2441
    }
2442
2443
    /**
2444
     * Builds the new klarna version-string.
2445
     *
2446
     * @param Klarna $klarna
2447
     * @return string
2448
     */
2449
    private function buildKlarnaVersion(Klarna $klarna)
2450
    {
2451
        $versionInfo = array(
2452
            'Shopware',
2453
            $this->Application()->Config()->version,
2454
            'KCO-Plugin',
2455
            $this->getVersion(),
2456
            $klarna->getVersion()
2457
        );
2458
2459
        return implode(':', $versionInfo);
2460
    }
2461
2462
    /**
2463
     * Helper method to find out if the kpm plugin is active
2464
     */
2465 View Code Duplication
    public function isKpmActive()
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...
2466
    {
2467
        /** @var Doctrine\DBAL\Query\QueryBuilder $queryBuilder */
2468
        $queryBuilder = Shopware()->Models()->getConnection()->createQueryBuilder();
2469
2470
        $result = $queryBuilder->select('plugin.id')
2471
            ->from('s_core_plugins', 'plugin')
2472
            ->where('plugin.name = :name')
2473
            ->andWhere('plugin.active = 1')
2474
            ->setParameter('name', 'SwagPaymentKlarnaKpm')
2475
            ->execute()
2476
            ->fetchColumn();
2477
2478
        return !empty($result);
2479
    }
2480
2481
    /**
2482
     * Helper method to find out if the kco paymentmean is active
2483
     */
2484 View Code Duplication
    public function isKcoPaymentActive()
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...
2485
    {
2486
        /** @var Doctrine\DBAL\Query\QueryBuilder $queryBuilder */
2487
        $queryBuilder = Shopware()->Models()->getConnection()->createQueryBuilder();
2488
2489
        $result = $queryBuilder->select('payment.id')
2490
            ->from('s_core_paymentmeans', 'payment')
2491
            ->where('payment.name = :name')
2492
            ->andWhere('payment.active = 1')
2493
            ->setParameter('name', 'klarna_checkout')
2494
            ->execute()
2495
            ->fetchColumn();
2496
2497
        return !empty($result);
2498
    }
2499
2500
    /**
2501
     * Helper method to find out if the klarna kco payment is active.
2502
     * Necessary to disable the checkout-button.
2503
     * @param array $user
2504
     * @return bool
2505
     */
2506
    public function isKlarnaKcoPaymentActive($user)
2507
    {
2508
        $payment = $this->getPayment();
2509
        if (!$payment) {
2510
            return false;
2511
        }
2512
        $data = $this->get('modules')->Admin()->sGetPaymentMeanById($payment->getId(), $user);
2513
        if (empty($data) || $data['id'] != $payment->getId()) {
2514
            return false;
2515
        }
2516
        return true;
2517
    }
2518
}
2519