Completed
Pull Request — master (#373)
by Jonas
03:04
created

Checkout   D

Complexity

Total Complexity 79

Size/Duplication

Total Lines 598
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 12

Importance

Changes 0
Metric Value
dl 0
loc 598
rs 4.7368
c 0
b 0
f 0
wmc 79
lcom 1
cbo 12

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 11 1
A getSubscribedEvents() 0 8 1
A updateSessionId() 0 4 1
A getCountryCode() 0 6 1
F fixBasketForConnect() 0 153 21
B translateConnectMessages() 0 22 4
F reserveConnectProductsOnCheckoutFinish() 0 127 21
C getDeliveryAddress() 0 35 7
A createDummyAddress() 0 13 1
B checkoutReservedProducts() 0 22 6
A enforcePhoneNumber() 0 12 4
A getNotAvailableMessageForProducts() 0 14 2
B getNotShippableMessages() 0 22 4
A setOrderStatusError() 0 14 1
A isPaymentAllowed() 0 20 4

How to fix   Complexity   

Complex Class

Complex classes like Checkout often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Checkout, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * (c) shopware AG <[email protected]>
4
 * For the full copyright and license information, please view the LICENSE
5
 * file that was distributed with this source code.
6
 */
7
8
namespace ShopwarePlugins\Connect\Subscribers;
9
10
use Enlight_Event_EventManager;
11
use Shopware\Components\Model\ModelManager;
12
use Shopware\Connect\Struct\Address;
13
use Shopware\Connect\Struct\CheckResult;
14
use Shopware\Connect\Struct\Message;
15
use Shopware\Connect\Struct\OrderItem;
16
use Shopware\Connect\Struct\Product;
17
use Shopware\Models\Order\Status;
18
use ShopwarePlugins\Connect\Components\ConnectFactory;
19
use ShopwarePlugins\Connect\Components\Exceptions\CheckoutException;
20
use ShopwarePlugins\Connect\Components\Logger;
21
use ShopwarePlugins\Connect\Components\Utils\ConnectOrderUtil;
22
use ShopwarePlugins\Connect\Components\Utils\OrderPaymentMapper;
23
24
/**
25
 * Handles the whole checkout manipulation, which is required for the connect checkout
26
 *
27
 * Class Checkout
28
 * @package ShopwarePlugins\Connect\Subscribers
29
 */
30
class Checkout extends BaseSubscriber
31
{
32
    /**
33
     * @var Logger
34
     */
35
    protected $logger;
36
37
    /**
38
     * @var string
39
     */
40
    private $newSessionId;
41
42
    /**
43
     * @var  ConnectFactory
44
     */
45
    protected $factory;
46
47
    /**
48
     * @var ModelManager
49
     */
50
    protected $manager;
51
52
    /**
53
     * @var Enlight_Event_EventManager
54
     */
55
    protected $eventManager;
56
57
    /**
58
     * @param ModelManager $manager
59
     */
60
    public function __construct(
61
        ModelManager $manager,
62
        Enlight_Event_EventManager $eventManager
63
    ) {
64
        parent::__construct();
65
66
        $this->manager = $manager;
67
        $this->eventManager = $eventManager;
68
        $this->logger = new Logger(Shopware()->Db());
69
        $this->factory = new ConnectFactory();
70
    }
71
72
    /**
73
     * @return array
74
     */
75
    public function getSubscribedEvents()
76
    {
77
        return [
78
            'Enlight_Controller_Action_PostDispatch_Frontend_Checkout' => 'fixBasketForConnect',
79
            'Enlight_Controller_Action_PreDispatch_Frontend_Checkout' => 'reserveConnectProductsOnCheckoutFinish',
80
            'Shopware_Modules_Admin_Regenerate_Session_Id' => 'updateSessionId',
81
        ];
82
    }
83
84
    /**
85
     * @param \Enlight_Event_EventArgs $args
86
     */
87
    public function updateSessionId(\Enlight_Event_EventArgs $args)
88
    {
89
        $this->newSessionId = $args->get('newSessionId');
90
    }
91
92
    /**
93
     * @return string
94
     */
95
    protected function getCountryCode()
96
    {
97
        $countryCodeUtil = $this->factory->getCountryCodeResolver();
98
99
        return $countryCodeUtil->getIso3CountryCode();
100
    }
101
102
    /**
103
     * Event listener method for the checkout confirm- and cartAction.
104
     *
105
     * @param \Enlight_Event_EventArgs $args
106
     * @throws CheckoutException
107
     * @return void
108
     */
109
    public function fixBasketForConnect(\Enlight_Event_EventArgs $args)
110
    {
111
        /** @var $action \Enlight_Controller_Action */
112
        $action = $args->getSubject();
113
        $view = $action->View();
114
        $request = $action->Request();
115
        $actionName = $request->getActionName();
116
        $sessionId = Shopware()->SessionID();
117
118
        $userId = Shopware()->Session()->sUserId;
119
        $hasConnectProduct = $this->getHelper()->hasBasketConnectProducts($sessionId, $userId);
120
121
        if ($hasConnectProduct === false && $this->newSessionId) {
122
            $hasConnectProduct = $this->getHelper()->hasBasketConnectProducts($this->newSessionId);
123
        }
124
125
        $view->hasConnectProduct = $hasConnectProduct;
126
127
        if ($actionName == 'ajax_add_article') {
128
            $this->registerMyTemplateDir();
129
            $view->extendsTemplate('frontend/connect/ajax_add_article.tpl');
130
        }
131
132
        // send order to connect
133
        // this method must be called after external payments (Sofort, Billsafe)
134
        if ($actionName == 'finish' && !empty($view->sOrderNumber)) {
135
            try {
136
                $this->checkoutReservedProducts($view->sOrderNumber);
137
            } catch (CheckoutException $e) {
138
                $this->setOrderStatusError($view->sOrderNumber);
139
                throw $e;
140
            }
141
        }
142
143
        // clear connect reserved products
144
        // sometimes with external payment methods
145
        // $hasConnectProduct will be false, because order is already finished
146
        // and information about connect products is not available.
147
        if (!$hasConnectProduct) {
148
            $this->getHelper()->clearConnectReservation();
149
150
            return;
151
        }
152
153
        if (!in_array($actionName, ['confirm', 'shippingPayment', 'cart', 'finish'])) {
154
            return;
155
        }
156
157
        if (empty($view->sBasket) || !$request->isDispatched()) {
158
            return;
159
        }
160
161
        if (!empty($view->sOrderNumber)) {
162
            return;
163
        }
164
165
        if (Shopware()->Config()->get('requirePhoneField')) {
166
            $this->enforcePhoneNumber($view);
167
        }
168
169
        $this->registerMyTemplateDir();
170
        if ($this->Application()->Container()->get('shop')->getTemplate()->getVersion() < 3) {
171
            $view->extendsTemplate('frontend/connect/checkout.tpl');
172
        }
173
174
        $sdk = $this->getSDK();
175
176
        // Wrap the basket array in order to make it some more readable
177
        $basketHelper = $this->getBasketHelper();
178
        $basketHelper->setBasket($view->sBasket);
179
180
        // If no messages are shown, yet, check products from remote shop and build message array
181
        if (($connectMessages = Shopware()->Session()->connectMessages) === null) {
182
            $connectMessages = [];
183
184
            $session = Shopware()->Session();
185
            $userData = $session['sOrderVariables']['sUserData'];
186
            // prepare an order to check products
187
            $order = new \Shopware\Connect\Struct\Order();
188
            $order->orderItems = [];
189
            $order->billingAddress = $order->deliveryAddress = $this->getDeliveryAddress($userData);
190
191
            $allProducts = [];
192
193
            foreach ($basketHelper->getConnectProducts() as $shopId => $products) {
194
                $products = $this->getHelper()->prepareConnectUnit($products);
195
                $allProducts = array_merge($allProducts, $products);
196
                // add order items in connect order
197
                $order->orderItems = array_map(function (Product $product) use ($basketHelper) {
198
                    return new OrderItem([
199
                        'product' => $product,
200
                        'count' => $basketHelper->getQuantityForProduct($product),
201
                    ]);
202
                }, $products);
203
            }
204
205
            $this->Application()->Container()->get('events')->notify(
206
                'Connect_Merchant_Create_Order_Before',
207
                [
208
                    //we use clone to not be able to modify the connect order
209
                    'order' => clone $order,
210
                    'basket' => $view->sBasket,
211
                ]
212
            );
213
214
            /** @var $checkResult \Shopware\Connect\Struct\CheckResult */
215
            try {
216
                $checkResult = $sdk->checkProducts($order);
217
                $basketHelper->setCheckResult($checkResult);
218
219
                if ($checkResult->hasErrors()) {
220
                    $connectMessages = $checkResult->errors;
221
                }
222
            } catch (\Exception $e) {
223
                $this->logger->write(true, 'Error during checkout', $e, 'checkout');
224
                // If the checkout results in an exception because the remote shop is not available
225
                // don't show the exception to the user but tell him to remove the products from that shop
226
                $connectMessages = $this->getNotAvailableMessageForProducts($allProducts);
227
            }
228
        }
229
230
        if ($connectMessages) {
231
            $connectMessages = $this->translateConnectMessages($connectMessages);
232
        }
233
234
        Shopware()->Session()->connectMessages = null;
235
236
        // If no products are bought from the local shop, move the first connect shop into
237
        // the content section. Also set that shop's id in the template
238
        $shopId = $basketHelper->fixBasket();
239
        if ($shopId) {
240
            $view->shopId = $shopId;
241
        }
242
        // Increase amount and shipping costs by the amount of connect shipping costs
243
        $basketHelper->recalculate($basketHelper->getCheckResult());
244
245
        $connectMessages = $this->getNotShippableMessages($basketHelper->getCheckResult(), $connectMessages);
246
247
        $view->assign($basketHelper->getDefaultTemplateVariables());
248
249
        // Set the sOrderVariables for the session based on the original content subarray of the basket array
250
        // @HL - docs?
251
        if ($actionName == 'confirm') {
252
            $session = Shopware()->Session();
253
            /** @var $variables \ArrayObject */
254
            $variables = $session->offsetGet('sOrderVariables');
255
256
            $session->offsetSet('sOrderVariables', $basketHelper->getOrderVariablesForSession($variables));
257
        }
258
259
        $view->assign($basketHelper->getConnectTemplateVariables($connectMessages));
260
        $view->assign('showShippingCostsSeparately', $this->factory->getConfigComponent()->getConfig('showShippingCostsSeparately', false));
261
    }
262
263
    /**
264
     * Helper to translate connect messages from the SDK. Will use the normalized message itself as namespace key
265
     *
266
     * @param $connectMessages
267
     * @return mixed
268
     */
269
    private function translateConnectMessages($connectMessages)
270
    {
271
        $namespace = Shopware()->Snippets()->getNamespace('frontend/checkout/connect');
272
273
        foreach ($connectMessages as &$connectMessage) {
274
            $message = trim($connectMessage->message);
275
            $normalized = strtolower(preg_replace('/[^a-zA-Z0-9]/', '_', $connectMessage->message));
276
            if (empty($normalized) || empty($message)) {
277
                $normalized = 'unknown-connect-error';
278
                $message = 'Unknown error';
279
            }
280
            $translation = $namespace->get(
281
                $normalized,
282
                $message,
283
                true
284
            );
285
286
            $connectMessage->message = $translation;
287
        }
288
289
        return $connectMessages;
290
    }
291
292
    /**
293
     * Event listener method for the checkout->finishAction. Will reserve products and redirect to
294
     * the confirm page if a product cannot be reserved
295
     *
296
     * @event Enlight_Controller_Action_PreDispatch_Frontend_Checkout
297
     * @param \Enlight_Event_EventArgs $args
298
     */
299
    public function reserveConnectProductsOnCheckoutFinish(\Enlight_Event_EventArgs $args)
300
    {
301
        /** @var $controller \Enlight_Controller_Action */
302
        $controller = $args->getSubject();
303
        $request = $controller->Request();
304
        $view = $controller->View();
305
        $session = Shopware()->Session();
306
        $sdk = $this->getSDK();
307
        $helper = $this->getHelper();
308
        $userData = $session['sOrderVariables']['sUserData'];
309
        $paymentName = $userData['additional']['payment']['name'];
310
311
        if (($request->getActionName() != 'finish' && $request->getActionName() != 'payment')) {
312
            if (($request->getActionName() == 'confirm' && $paymentName == 'klarna_checkout')) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
313
                // BEP-1010 Fix for Klarna checkout
314
            } else {
315
                return;
316
            }
317
        }
318
319
        if (empty($session['sOrderVariables'])) {
320
            return;
321
        }
322
323
        if (!$this->getHelper()->hasBasketConnectProducts(Shopware()->SessionID())) {
324
            return;
325
        }
326
327
        $userData = $session['sOrderVariables']['sUserData'];
328
        $paymentId = $userData['additional']['payment']['id'];
329
330
        if ($this->isPaymentAllowed($paymentId) === false) {
331
            $connectMessage = new \stdClass();
332
            $connectMessage->message = 'frontend_checkout_cart_connect_payment_not_allowed';
333
334
            $connectMessages = [
335
                0 => [
336
                    'connectmessage' => $connectMessage
337
                ]
338
            ];
339
340
            Shopware()->Session()->connectMessages = $this->translateConnectMessages($connectMessages);
341
            $controller->forward('confirm');
342
        }
343
344
        if (Shopware()->Config()->get('requirePhoneField')) {
345
            $this->enforcePhoneNumber($view);
346
        }
347
348
        $order = new \Shopware\Connect\Struct\Order();
349
        $order->orderItems = [];
350
        $order->deliveryAddress = $this->getDeliveryAddress($userData);
351
352
        $basket = $session['sOrderVariables']['sBasket'];
353
354
        /** @var \ShopwarePlugins\Connect\Components\Utils\OrderPaymentMapper $orderPaymentMapper */
355
        $orderPaymentMapper = new OrderPaymentMapper();
356
        $orderPaymentName = $userData['additional']['payment']['name'];
357
        $order->paymentType = $orderPaymentMapper->mapShopwareOrderPaymentToConnect($orderPaymentName);
358
359
        foreach ($basket['content'] as $row) {
360
            if (!empty($row['mode'])) {
361
                continue;
362
            }
363
364
            $articleDetailId = $row['additional_details']['articleDetailsID'];
365
            if ($helper->isRemoteArticleDetailDBAL($articleDetailId) === false) {
366
                continue;
367
            }
368
            $shopProductId = $helper->getShopProductId($articleDetailId);
369
370
            $products = $helper->getRemoteProducts([$shopProductId->sourceId], $shopProductId->shopId);
371
            $products = $this->getHelper()->prepareConnectUnit($products);
372
373
            if (empty($products)) {
374
                continue;
375
            }
376
            $product = $products[0];
377
378
379
            if ($product === null || $product->shopId === null) {
380
                continue;
381
            }
382
383
            $orderItem = new \Shopware\Connect\Struct\OrderItem();
384
            $orderItem->product = $product;
385
            $orderItem->count = (int) $row['quantity'];
386
            $order->orderItems[] = $orderItem;
387
        }
388
389
        if (empty($order->orderItems)) {
390
            return;
391
        }
392
393
        try {
394
            $order = $this->eventManager->filter(
395
                'Connect_Subscriber_OrderReservation_OrderFilter',
396
                $order
397
            );
398
399
            /** @var $reservation \Shopware\Connect\Struct\Reservation */
400
            $reservation = $sdk->reserveProducts($order);
401
402
            if (!$reservation || !$reservation->success) {
403
                throw new \Exception('Error during reservation');
404
            }
405
406
            if (!empty($reservation->messages)) {
407
                $messages = $reservation->messages;
408
            }
409
        } catch (\Exception $e) {
410
            $this->logger->write(true, 'Error during reservation', $e, 'reservation');
411
            $messages = $this->getNotAvailableMessageForProducts(array_map(
412
                function ($orderItem) {
413
                    return $orderItem->product;
414
                },
415
                $order->orderItems
416
            ));
417
        }
418
419
        if (!empty($messages)) {
420
            Shopware()->Session()->connectMessages = $messages;
421
            $controller->forward('confirm');
422
        } else {
423
            Shopware()->Session()->connectReservation = serialize($reservation);
0 ignored issues
show
Bug introduced by
The variable $reservation does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
424
        }
425
    }
426
427
    /**
428
     * Helper method to create an address struct from shopware session info
429
     *
430
     * @param $userData
431
     * @return Address
432
     */
433
    private function getDeliveryAddress($userData)
434
    {
435
        if (!$userData) {
436
            return $this->createDummyAddress('DEU');
437
        }
438
439
        $shippingData = $userData['shippingaddress'];
440
        $address = new Address();
441
        $address->zip = $shippingData['zipcode'];
442
        $address->city = $shippingData['city'];
443
        $address->country = $userData['additional']['countryShipping']['iso3']; //when the user is not logged in
444
        $address->phone = $userData['billingaddress']['phone'];
445
        $address->email = $userData['additional']['user']['email'];
446
        if (!empty($userData['additional']['stateShipping']['shortcode'])) {
447
            $address->state = $userData['additional']['stateShipping']['shortcode'];
448
        }
449
        if (!empty($shippingData['department'])) {
450
            $address->department = $shippingData['department'];
451
        }
452
        if (!empty($shippingData['additionalAddressLine1'])) {
453
            $address->additionalAddressLine1 = $shippingData['additionalAddressLine1'];
0 ignored issues
show
Bug introduced by
The property additionalAddressLine1 does not seem to exist. Did you mean additionalAddressLine?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
454
        }
455
        if (!empty($shippingData['additionalAddressLine2'])) {
456
            $address->additionalAddressLine2 = $shippingData['additionalAddressLine2'];
0 ignored issues
show
Bug introduced by
The property additionalAddressLine2 does not seem to exist. Did you mean additionalAddressLine?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
457
        }
458
        $address->firstName = $shippingData['firstname'];
459
        $address->surName = $shippingData['lastname'];
460
        if (!empty($shippingData['company'])) {
461
            $address->company = $shippingData['company'];
462
        }
463
        $address->street = $shippingData['street'];
464
        $address->streetNumber = (string) $shippingData['streetnumber'];
465
466
        return $address;
467
    }
468
469
    /**
470
     * @param string $country
471
     * @return Address
472
     */
473
    private function createDummyAddress($country = 'DEU')
474
    {
475
        return new Address([
476
            'country' => $country,
477
            'firstName' => 'Shopware',
478
            'surName' => 'AG',
479
            'street' => 'Eggeroder Str. 6',
480
            'zip' => '48624',
481
            'city' => 'Schöppingen',
482
            'phone' => '+49 (0) 2555 92885-0',
483
            'email' => '[email protected]'
484
        ]);
485
    }
486
487
    /**
488
     * Hooks the sSaveOrder frontend method and reserves the connect products
489
     *
490
     * @param $orderNumber
491
     * @throws \ShopwarePlugins\Connect\Components\Exceptions\CheckoutException
492
     */
493
    public function checkoutReservedProducts($orderNumber)
494
    {
495
        $sdk = $this->getSDK();
496
497
        if (empty($orderNumber)) {
498
            return;
499
        }
500
501
        $reservation = unserialize(Shopware()->Session()->connectReservation);
502
503
        if ($reservation !== null && $reservation !== false) {
504
            $result = $sdk->checkout($reservation, $orderNumber);
505
            foreach ($result as $shopId => $success) {
506
                if (!$success) {
507
                    $e = new CheckoutException("Could not checkout from warehouse {$shopId}");
508
                    $this->logger->write(true, 'Error during checkout with this reservation: ' . json_encode($reservation, JSON_PRETTY_PRINT), $e, 'checkout');
509
                    throw $e;
510
                }
511
            }
512
            $this->getHelper()->clearConnectReservation();
513
        }
514
    }
515
516
    /**
517
     * Asks the user to leave is phone number if connect products are in the basket and the
518
     * phone number was not configured, yet.
519
     *
520
     * @param \Enlight_View_Default $view
521
     * @return null
522
     */
523
    public function enforcePhoneNumber($view)
524
    {
525
        if (Shopware()->Session()->sUserId && $this->getHelper()->hasBasketConnectProducts(Shopware()->SessionID())) {
526
            $id = Shopware()->Session()->sUserId;
527
528
            $sql = 'SELECT phone FROM s_user_billingaddress WHERE userID = :id';
529
            $result = Shopware()->Db()->fetchOne($sql, ['id' => $id]);
530
            if (!$result) {
531
                $view->assign('phoneMissing', true);
532
            }
533
        }
534
    }
535
536
    /**
537
     * @param Product[] $products
538
     * @return array
539
     */
540
    protected function getNotAvailableMessageForProducts($products)
541
    {
542
        $messages = [];
543
        foreach ($products as $product) {
544
            $messages[] = new Message([
545
                'message' => 'Due to technical reasons, product %product is not available.',
546
                'values' => [
547
                    'product' => $product->title,
548
                ]
549
            ]);
550
        }
551
552
        return $messages;
553
    }
554
555
    /**
556
     * @param \Shopware\Connect\Struct\CheckResult $checkResult
557
     * @param $connectMessages
558
     * @return mixed
559
     */
560
    protected function getNotShippableMessages($checkResult, $connectMessages)
561
    {
562
        if (!$checkResult instanceof CheckResult) {
563
            return $connectMessages;
564
        }
565
566
        $namespace = Shopware()->Snippets()->getNamespace('frontend/checkout/connect');
567
568
        foreach ($checkResult->shippingCosts as $shipping) {
569
            if ($shipping->isShippable === false) {
570
                $connectMessages[] = new Message([
571
                    'message' => $namespace->get(
572
                            'frontend_checkout_cart_connect_not_shippable',
573
                            'Ihre Bestellung kann nicht geliefert werden',
574
                            true
575
                        )
576
                ]);
577
            }
578
        }
579
580
        return $connectMessages;
581
    }
582
583
    /**
584
     * @param $orderNumber
585
     * @return void
586
     */
587
    private function setOrderStatusError($orderNumber)
588
    {
589
        $repo = $this->manager->getRepository('Shopware\Models\Order\Order');
590
591
        /** @var \Shopware\Models\Order\Order $order */
592
        $order = $repo->findOneBy(['number' => $orderNumber]);
593
594
        $repoStatus = $this->manager->getRepository(Status::class);
595
        $status = $repoStatus->findOneBy(['name' => ConnectOrderUtil::ORDER_STATUS_ERROR, 'group' => Status::GROUP_STATE ]);
596
597
        $order->setOrderStatus($status);
598
        $this->manager->persist($order);
599
        $this->manager->flush();
600
    }
601
602
    /**
603
     * Check is allowed payment method with connect products
604
     * @param int $paymentId
605
     * @return bool
606
     */
607
    private function isPaymentAllowed($paymentId)
608
    {
609
        if ($paymentId < 1) {
610
            return false;
611
        }
612
613
        $paymentRepository = Shopware()->Models()->getRepository('Shopware\Models\Payment\Payment');
614
        /** @var \Shopware\Models\Payment\Payment $payment */
615
        $payment = $paymentRepository->find($paymentId);
616
617
        if (!$payment) {
618
            return false;
619
        }
620
621
        if ($payment->getAttribute()->getConnectIsAllowed() == 0) {
622
            return false;
623
        }
624
625
        return true;
626
    }
627
}
628