Passed
Push — master ( 17e2f0...fa70ba )
by Florian
02:22
created

LoadReview::handleCouponRequest()   C

Complexity

Conditions 15
Paths 178

Size

Total Lines 58
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 15
eloc 33
c 1
b 0
f 0
nc 178
nop 0
dl 0
loc 58
rs 5.2666

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 * PAYONE Magento 2 Connector is free software: you can redistribute it and/or modify
5
 * it under the terms of the GNU Lesser General Public License as published by
6
 * the Free Software Foundation, either version 3 of the License, or
7
 * (at your option) any later version.
8
 *
9
 * PAYONE Magento 2 Connector is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 * GNU Lesser General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Lesser General Public License
15
 * along with PAYONE Magento 2 Connector. If not, see <http://www.gnu.org/licenses/>.
16
 *
17
 * PHP version 5
18
 *
19
 * @category  Payone
20
 * @package   Payone_Magento2_Plugin
21
 * @author    FATCHIP GmbH <[email protected]>
22
 * @copyright 2003 - 2018 Payone GmbH
23
 * @license   <http://www.gnu.org/licenses/> GNU Lesser General Public License
24
 * @link      http://www.payone.de
25
 */
26
27
namespace Payone\Core\Controller\Amazon;
28
29
use Magento\Framework\App\ResponseInterface;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\App\ResponseInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
30
use Magento\Framework\Controller\Result\Json;
0 ignored issues
show
Bug introduced by
The type Magento\Framework\Controller\Result\Json was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
31
use Payone\Core\Model\Exception\AuthorizationException;
32
use Payone\Core\Model\PayoneConfig;
33
use Magento\Quote\Model\Quote;
0 ignored issues
show
Bug introduced by
The type Magento\Quote\Model\Quote was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
34
use Magento\Checkout\Model\Type\Onepage;
0 ignored issues
show
Bug introduced by
The type Magento\Checkout\Model\Type\Onepage was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
35
use Magento\Customer\Model\Group;
0 ignored issues
show
Bug introduced by
The type Magento\Customer\Model\Group was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
36
37
/**
38
 * TransactionStatus receiver
39
 */
40
class LoadReview extends \Magento\Framework\App\Action\Action
0 ignored issues
show
Bug introduced by
The type Magento\Framework\App\Action\Action was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
41
{
42
    /**
43
     * Result factory
44
     *
45
     * @var \Magento\Framework\Controller\Result\JsonFactory
0 ignored issues
show
Bug introduced by
The type Magento\Framework\Controller\Result\JsonFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
46
     */
47
    protected $resultJsonFactory;
48
49
    /**
50
     * @var \Payone\Core\Block\Onepage\Review
51
     */
52
    protected $reviewBlock;
53
54
    /**
55
     * Page result factory
56
     *
57
     * @var \Magento\Framework\View\Result\PageFactory
0 ignored issues
show
Bug introduced by
The type Magento\Framework\View\Result\PageFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
58
     */
59
    protected $pageFactory;
60
61
    /**
62
     * Checkout session
63
     *
64
     * @var \Magento\Checkout\Model\Session
0 ignored issues
show
Bug introduced by
The type Magento\Checkout\Model\Session was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
65
     */
66
    protected $checkoutSession;
67
68
    /**
69
     * @var \Magento\Checkout\Model\Cart
0 ignored issues
show
Bug introduced by
The type Magento\Checkout\Model\Cart was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
70
     */
71
    protected $cart;
72
73
    /**
74
     * @var \Magento\Quote\Api\CartRepositoryInterface
0 ignored issues
show
Bug introduced by
The type Magento\Quote\Api\CartRepositoryInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
75
     */
76
    protected $quoteRepository;
77
78
    /**
79
     * Coupon factory
80
     *
81
     * @var \Magento\SalesRule\Model\CouponFactory
0 ignored issues
show
Bug introduced by
The type Magento\SalesRule\Model\CouponFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
82
     */
83
    protected $couponFactory;
84
85
    /**
86
     * Object of getconfiguration request
87
     *
88
     * @var \Payone\Core\Model\Api\Request\Genericpayment\GetConfiguration
89
     */
90
    protected $getConfiguration;
91
92
    /**
93
     * Object of getorderreferencedetails request
94
     *
95
     * @var \Payone\Core\Model\Api\Request\Genericpayment\GetOrderReferenceDetails
96
     */
97
    protected $getOrderReferenceDetails;
98
99
    /**
100
     * Object of setorderreferencedetails request
101
     *
102
     * @var \Payone\Core\Model\Api\Request\Genericpayment\SetOrderReferenceDetails
103
     */
104
    protected $setOrderReferenceDetails;
105
106
    /**
107
     * Object of setorderreferencedetails request
108
     *
109
     * @var \Payone\Core\Model\Api\Request\Genericpayment\ConfirmOrderReference
110
     */
111
    protected $confirmOrderReference;
112
113
    /**
114
     * Amazon Pay payment object
115
     *
116
     * @var \Payone\Core\Model\Methods\AmazonPay
117
     */
118
    protected $payment;
119
120
    /**
121
     * PAYONE order helper
122
     *
123
     * @var \Payone\Core\Helper\Order
124
     */
125
    protected $orderHelper;
126
127
    /**
128
     * PAYONE order helper
129
     *
130
     * @var \Payone\Core\Helper\Checkout
131
     */
132
    protected $checkoutHelper;
133
134
    /**
135
     * Cart management interface
136
     *
137
     * @var \Magento\Quote\Api\CartManagementInterface
0 ignored issues
show
Bug introduced by
The type Magento\Quote\Api\CartManagementInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
138
     */
139
    protected $cartManagement;
140
141
    /**
142
     * Existing Payone error codes mapped to their Amazon error codes
143
     *
144
     * @var array
145
     */
146
    protected $amazonErrors = [
147
        109 => 'AmazonRejected',
148
        900 => 'UnspecifiedError',
149
        980 => 'TransactionTimedOut',
150
        981 => 'InvalidPaymentMethod',
151
        982 => 'AmazonRejected',
152
        983 => 'ProcessingFailure',
153
        984 => 'BuyerEqualsSeller',
154
        985 => 'PaymentMethodNotAllowed',
155
        986 => 'PaymentPlanNotSet',
156
        987 => 'ShippingAddressNotSet'
157
    ];
158
159
    /**
160
     * Constructor
161
     *
162
     * @param \Magento\Framework\App\Action\Context                                  $context
163
     * @param \Magento\Framework\Controller\Result\JsonFactory                       $resultJsonFactory
164
     * @param \Payone\Core\Block\Onepage\Review                                      $reviewBlock
165
     * @param \Magento\Framework\View\Result\PageFactory                             $pageFactory
166
     * @param \Magento\Checkout\Model\Session                                        $checkoutSession
167
     * @param \Magento\Checkout\Model\Cart                                           $cart
168
     * @param \Magento\Quote\Api\CartRepositoryInterface                             $quoteRepository
169
     * @param \Magento\SalesRule\Model\CouponFactory                                 $couponFactory
170
     * @param \Payone\Core\Model\Api\Request\Genericpayment\GetConfiguration         $getConfiguration
171
     * @param \Payone\Core\Model\Api\Request\Genericpayment\GetOrderReferenceDetails $getOrderReferenceDetails
172
     * @param \Payone\Core\Model\Api\Request\Genericpayment\SetOrderReferenceDetails $setOrderReferenceDetails
173
     * @param \Payone\Core\Model\Api\Request\Genericpayment\ConfirmOrderReference    $confirmOrderReference
174
     * @param \Payone\Core\Model\Methods\AmazonPay                                   $payment
175
     * @param \Payone\Core\Helper\Order                                              $orderHelper
176
     * @param \Payone\Core\Helper\Checkout                                           $checkoutHelper
177
     * @param \Magento\Quote\Api\CartManagementInterface                             $cartManagement
178
     */
179
    public function __construct(
180
        \Magento\Framework\App\Action\Context $context,
0 ignored issues
show
Bug introduced by
The type Magento\Framework\App\Action\Context was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
181
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
182
        \Payone\Core\Block\Onepage\Review $reviewBlock,
183
        \Magento\Framework\View\Result\PageFactory $pageFactory,
184
        \Magento\Checkout\Model\Session $checkoutSession,
185
        \Magento\Checkout\Model\Cart $cart,
186
        \Magento\Quote\Api\CartRepositoryInterface $quoteRepository,
187
        \Magento\SalesRule\Model\CouponFactory $couponFactory,
188
        \Payone\Core\Model\Api\Request\Genericpayment\GetConfiguration $getConfiguration,
189
        \Payone\Core\Model\Api\Request\Genericpayment\GetOrderReferenceDetails $getOrderReferenceDetails,
190
        \Payone\Core\Model\Api\Request\Genericpayment\SetOrderReferenceDetails $setOrderReferenceDetails,
191
        \Payone\Core\Model\Api\Request\Genericpayment\ConfirmOrderReference $confirmOrderReference,
192
        \Payone\Core\Model\Methods\AmazonPay $payment,
193
        \Payone\Core\Helper\Order $orderHelper,
194
        \Payone\Core\Helper\Checkout $checkoutHelper,
195
        \Magento\Quote\Api\CartManagementInterface $cartManagement
196
    ) {
197
        parent::__construct($context);
198
        $this->resultJsonFactory = $resultJsonFactory;
199
        $this->reviewBlock = $reviewBlock;
200
        $this->pageFactory = $pageFactory;
201
        $this->checkoutSession = $checkoutSession;
202
        $this->cart = $cart;
203
        $this->quoteRepository = $quoteRepository;
204
        $this->couponFactory = $couponFactory;
205
        $this->getConfiguration = $getConfiguration;
206
        $this->getOrderReferenceDetails = $getOrderReferenceDetails;
207
        $this->setOrderReferenceDetails = $setOrderReferenceDetails;
208
        $this->confirmOrderReference = $confirmOrderReference;
209
        $this->payment = $payment;
210
        $this->orderHelper = $orderHelper;
211
        $this->checkoutHelper = $checkoutHelper;
212
        $this->cartManagement = $cartManagement;
213
    }
214
215
    /**
216
     * Executing TransactionStatus handling
217
     *
218
     * @return Json|ResponseInterface
219
     */
220
    public function execute()
221
    {
222
        $aReturnData = [];
223
224
        $blSuccess = false;
225
226
        $sAction = rtrim($this->getRequest()->getParam('action'), '/');
227
        switch ($sAction) {
228
            case 'confirmSelection':
229
                $aReturnData = $this->confirmSelection($aReturnData);
230
                if (!empty($aReturnData['workorderId'])) {
231
                    $blSuccess = true;
232
                }
233
                break;
234
            case 'confirmOrderReference':
235
                $aReturnData = $this->confirmOrderReference();
236
                if (isset($aReturnData['status']) && $aReturnData['status'] == 'OK') {
237
                    $blSuccess = true;
238
                }
239
                break;
240
            case 'placeOrder':
241
                $aReturnData = $this->placeOrder($aReturnData);
242
                if (!empty($aReturnData['redirectUrl'])) {
243
                    return $this->_redirect($aReturnData['redirectUrl']);
244
                }
245
                break;
246
            case 'updateShipping':
247
                $blSuccess = $this->updateShippingMethod($this->getRequest()->getParam('shippingMethod'));
248
                break;
249
            case 'updateCoupon':
250
                $blSuccess = $this->handleCouponRequest();
251
                break;
252
            case 'cancelToBasket':
253
                $this->messageManager->addErrorMessage(__('Sorry, your transaction with Amazon Pay was not successful. Please choose another payment method.'));
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

253
                $this->messageManager->addErrorMessage(/** @scrutinizer ignore-call */ __('Sorry, your transaction with Amazon Pay was not successful. Please choose another payment method.'));
Loading history...
254
                return $this->_redirect('checkout/cart');
255
        }
256
257
        if ($sAction != 'placeOrder' || empty($aReturnData['successUrl'])) {
258
            $oPageReturn = $this->pageFactory->create(false, ['template' => 'Payone_Core::blank.phtml']);
259
260
            $aReturnData['html'] = $oPageReturn->getLayout()->getOutput();
261
        }
262
263
        $aReturnData['success'] = $blSuccess;
264
265
        $resultJson = $this->resultJsonFactory->create();
266
        return $resultJson->setData($aReturnData);
267
    }
268
269
    /**
270
     * Get Amazon workorder_id from session or request
271
     *
272
     * @return string
273
     */
274
    protected function collectWorkorderId()
275
    {
276
        $sWorkorderId = $this->checkoutSession->getAmazonWorkorderId();
277
        if (empty($sWorkorderId)) {
278
            $aResult = $this->getConfiguration->sendRequest($this->payment);
279
            if (isset($aResult['status']) && $aResult['status'] == 'OK' && isset($aResult['workorderid'])) {
280
                $sWorkorderId = $aResult['workorderid'];
281
                $this->checkoutSession->setAmazonWorkorderId($aResult['workorderid']);
282
            }
283
        }
284
        return $sWorkorderId;
285
    }
286
287
    /**
288
     * Update shipping method
289
     *
290
     * @param  string $sShippingMethod
291
     * @return bool
292
     */
293
    protected function updateShippingMethod($sShippingMethod)
294
    {
295
        $oQuote = $this->checkoutSession->getQuote();
296
        $oShippingAddress = $oQuote->getShippingAddress();
297
        if (!$oQuote->getIsVirtual() && $oShippingAddress) {
298
            if ($sShippingMethod != $oShippingAddress->getShippingMethod()) {
299
                $this->ignoreAddressValidation($oQuote);
300
                $oShippingAddress->setShippingMethod($sShippingMethod)->setCollectShippingRates(true);
301
                $cartExtension = $oQuote->getExtensionAttributes();
302
                if ($cartExtension && $cartExtension->getShippingAssignments()) {
303
                    $cartExtension->getShippingAssignments()[0]->getShipping()->setMethod($sShippingMethod);
304
                }
305
                $oQuote->collectTotals();
306
                $this->quoteRepository->save($oQuote);
307
            }
308
        }
309
        return true;
310
    }
311
312
    /**
313
     * Disable validation to make sure addresses will always be saved
314
     *
315
     * @param  Quote $oQuote
316
     * @return void
317
     */
318
    protected function ignoreAddressValidation(Quote $oQuote)
319
    {
320
        $oQuote->getBillingAddress()->setShouldIgnoreValidation(true);
321
        if (!$oQuote->getIsVirtual()) {
322
            $oQuote->getShippingAddress()->setShouldIgnoreValidation(true);
323
        }
324
    }
325
326
    /**
327
     * Handle coupon management
328
     *
329
     * @return bool
330
     */
331
    protected function handleCouponRequest()
332
    {
333
        $couponCode = '';
334
        if ($this->getRequest()->getParam('remove') != 1) {
335
            $couponCode = trim($this->getRequest()->getParam('couponCode'));
336
        }
337
338
        $cartQuote = $this->checkoutSession->getQuote();
339
        $oldCouponCode = $cartQuote->getCouponCode();
340
341
        $codeLength = strlen($couponCode);
342
        if (!$codeLength && !strlen($oldCouponCode)) {
343
            return true;
344
        }
345
346
        try {
347
            $isCodeLengthValid = $codeLength && $codeLength <= \Magento\Checkout\Helper\Cart::COUPON_CODE_MAX_LENGTH;
0 ignored issues
show
Bug introduced by
The type Magento\Checkout\Helper\Cart was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
348
349
            $itemsCount = $cartQuote->getItemsCount();
350
            if ($itemsCount) {
351
                $cartQuote->getShippingAddress()->setCollectShippingRates(true);
352
                $cartQuote->setCouponCode($isCodeLengthValid ? $couponCode : '')->collectTotals();
353
                $this->quoteRepository->save($cartQuote);
354
            }
355
356
            if ($codeLength) {
357
                #$escaper = $this->_objectManager->get('Magento\Framework\Escaper');
358
                if (!$itemsCount) {
359
                    if ($isCodeLengthValid) {
360
                        $coupon = $this->couponFactory->create();
361
                        $coupon->load($couponCode, 'code');
362
                        if ($coupon->getId()) {
363
                            $this->checkoutSession->getQuote()->setCouponCode($couponCode)->save();
364
                            //$this->messageManager->addSuccess(__('You used coupon code "%1".', $escaper->escapeHtml($couponCode)));
365
                        } else {
366
                            //$this->messageManager->addError(__('The coupon code "%1" is not valid.', $escaper->escapeHtml($couponCode)));
367
                        }
368
                    } else {
369
                        //$this->messageManager->addError(__('The coupon code "%1" is not valid.', $escaper->escapeHtml($couponCode)));
370
                    }
371
                } else {
372
                    if ($isCodeLengthValid && $couponCode == $cartQuote->getCouponCode()) {
373
                        //$this->messageManager->addSuccess(__('You used coupon code "%1".', $escaper->escapeHtml($couponCode)));
374
                    } else {
375
                        //$this->messageManager->addError(__('The coupon code "%1" is not valid.', $escaper->escapeHtml($couponCode)));
376
                        $this->cart->save();
377
                    }
378
                }
379
            } else {
380
                //$this->messageManager->addSuccess(__('You canceled the coupon code.'));
381
            }
382
        } catch (\Magento\Framework\Exception\LocalizedException $e) {
0 ignored issues
show
Bug introduced by
The type Magento\Framework\Exception\LocalizedException was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
383
            $this->messageManager->addError($e->getMessage());
384
        } catch (\Exception $e) {
385
            //$this->messageManager->addError(__('We cannot apply the coupon code.'));
386
            //$this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
387
        }
388
        return true;
389
    }
390
391
    /**
392
     * confirmSelection action
393
     * Executes getorderreference details
394
     *
395
     * @param  array $aReturnData
396
     * @return array
397
     */
398
    protected function confirmSelection($aReturnData)
399
    {
400
        $sWorkorderId = $this->collectWorkorderId();
401
        if (!empty($sWorkorderId)) {
402
            $amazonReferenceId = $this->getRequest()->getParam('amazonReferenceId');
403
            $amazonAddressToken = $this->getRequest()->getParam('amazonAddressToken');
404
405
            $aResult = $this->getOrderReferenceDetails->sendRequest($this->payment, $sWorkorderId, $amazonReferenceId, $amazonAddressToken);
406
            if (isset($aResult['status']) && $aResult['status'] == 'OK') {
407
                $this->checkoutSession->setAmazonAddressToken($amazonAddressToken);
408
                $this->checkoutSession->setAmazonReferenceId($amazonReferenceId);
409
410
                $oQuote = $this->checkoutSession->getQuote();
411
                $oQuote = $this->orderHelper->updateAddresses($oQuote, $aResult);
412
413
                $oPayment = $oQuote->getPayment();
414
                $oPayment->setMethod(PayoneConfig::METHOD_AMAZONPAY);
415
416
                $oQuote->collectTotals()->save();
417
            }
418
        }
419
        $aReturnData['workorderId'] = $sWorkorderId;
420
421
        return $aReturnData;
422
    }
423
424
    /**
425
     * Return error identifier for given error code
426
     *
427
     * @param  int $iErrorCode
428
     * @return string
429
     */
430
    protected function getErrorIdentifier($iErrorCode)
431
    {
432
        $sIdentifier = 'UnknownError';
433
        if (isset($this->amazonErrors[$iErrorCode])) {
434
            $sIdentifier = $this->amazonErrors[$iErrorCode];
435
        }
436
        return $sIdentifier;
437
    }
438
439
    /**
440
     * confirmOrderReference action
441
     *
442
     * @return array
443
     */
444
    protected function confirmOrderReference()
445
    {
446
        $oQuote = $this->checkoutSession->getQuote();
447
448
        $sWorkorderId = $this->checkoutSession->getAmazonWorkorderId();
449
        $amazonReferenceId = $this->checkoutSession->getAmazonReferenceId();
450
        $amazonAddressToken = $this->checkoutSession->getAmazonAddressToken();
451
452
        if (!$this->checkoutSession->getOrderReferenceDetailsExecuted()) {
453
            $aResult = $this->setOrderReferenceDetails->sendRequest($this->payment, $oQuote->getGrandTotal(), $sWorkorderId, $amazonReferenceId, $amazonAddressToken);
454
            if (!isset($aResult['status']) || $aResult['status'] != 'OK') {
455
                $aResult['request'] = 'setOrderReferenceDetails';
456
                return $aResult;
457
            }
458
        }
459
460
        $this->checkoutSession->setOrderReferenceDetailsExecuted(true);
461
462
        $aResult = $this->confirmOrderReference->sendRequest($this->payment, $oQuote, $oQuote->getGrandTotal(), $sWorkorderId, $amazonReferenceId);
463
        $aResult['request'] = 'confirmOrderReference';
464
        return $aResult;
465
    }
466
467
    /**
468
     * placeOrder action
469
     * Generates the order
470
     *
471
     * @param  array $aReturnData
472
     * @return array
473
     */
474
    protected function placeOrder($aReturnData)
475
    {
476
        try {
477
            $oQuote = $this->checkoutSession->getQuote();
478
479
            if ($this->checkoutHelper->getCurrentCheckoutMethod($oQuote) == Onepage::METHOD_GUEST) {
480
                $oQuote->setCustomerId(null)
481
                    ->setCustomerEmail($oQuote->getBillingAddress()->getEmail())
482
                    ->setCustomerIsGuest(true)
483
                    ->setCustomerGroupId(Group::NOT_LOGGED_IN_ID);
484
            }
485
486
            #$oQuote->setPayment($oPayment);
487
            $oQuote->setInventoryProcessed(false);
488
            $oQuote->getBillingAddress()->setShouldIgnoreValidation(true);
489
            $oQuote->getShippingAddress()->setShouldIgnoreValidation(true);
490
            $oQuote->collectTotals()->save();
491
            $this->cartManagement->placeOrder($oQuote->getId());
492
            $oQuote->setIsActive(false)->save();
493
494
            $this->unsetSessionVariables();
495
496
            $aReturnData['redirectUrl'] = $this->_url->getUrl('checkout/onepage/success/');
497
        } catch (AuthorizationException $e) {
498
            $aResponse = $e->getResponse();
499
            $aReturnData['errorMessage'] = $this->getErrorIdentifier($aResponse['errorcode']);
500
            if (isset($aResponse['status']) && $aResponse['status'] == 'ERROR') {
501
                if (isset($aResponse['status']) && $aResponse['status'] == 'ERROR' && in_array($aResponse['errorcode'], [981, 985])) {
502
                    $this->messageManager->addErrorMessage('Please choose another payment method.');
503
                    $aReturnData['redirectUrl'] = $this->_url->getUrl('checkout/cart');
504
                    $this->unsetSessionVariables();
505
                } elseif (isset($aResponse['status']) && $aResponse['status'] == 'ERROR' && in_array($aResponse['errorcode'], [980, 982])) {
506
                    $aReturnData['redirectUrl'] = $this->_url->getUrl('payone/amazon/loadReview', ['action' => 'cancelToBasket']);
507
                    $this->unsetSessionVariables();
508
                }
509
            }
510
        } catch (\Exception $e) {
511
            //error_log($e->getMessage());
512
            $aReturnData['errorMessage'] = __('There has been an error processing your request.');
0 ignored issues
show
Bug introduced by
The function __ was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

512
            $aReturnData['errorMessage'] = /** @scrutinizer ignore-call */ __('There has been an error processing your request.');
Loading history...
513
            $aReturnData['redirectUrl'] = $this->_url->getUrl('payone/onepage/cancel?error=1');
514
        }
515
        return $aReturnData;
516
    }
517
518
    /**
519
     * Removes the amazon session variables
520
     *
521
     * @return void
522
     */
523
    protected function unsetSessionVariables()
524
    {
525
        $this->checkoutSession->unsAmazonWorkorderId();
526
        $this->checkoutSession->unsAmazonReferenceId();
527
        $this->checkoutSession->unsAmazonAddressToken();
528
        $this->checkoutSession->unsOrderReferenceDetailsExecuted();
529
    }
530
}
531