Completed
Push — master ( e76a9e...dfb6ec )
by
unknown
24s queued 12s
created

IndexV2::blockConcurrency()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 34
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 26
c 1
b 0
f 0
nc 10
nop 0
dl 0
loc 34
rs 8.8817
1
<?php
2
3
namespace Pagantis\Pagantis\Controller\Notify;
4
5
use Magento\Quote\Model\QuoteManagement;
6
use Magento\Quote\Api\Data\PaymentInterface;
7
use Magento\Sales\Api\Data\OrderInterface;
8
use Magento\Sales\Api\OrderRepositoryInterface;
9
use Magento\Quote\Model\Quote;
10
use Magento\Quote\Model\QuoteRepository;
11
use Magento\Framework\App\Action\Context;
12
use Magento\Framework\App\Action\Action;
13
use Pagantis\ModuleUtils\Exception\MerchantOrderNotFoundException;
14
use Pagantis\OrdersApiClient\Client;
15
use Pagantis\Pagantis\Helper\Config;
16
use Pagantis\Pagantis\Helper\ExtraConfig;
17
use Magento\Framework\App\ResourceConnection;
18
use Magento\Checkout\Model\Session;
19
use Magento\Framework\DB\Ddl\Table;
20
use Pagantis\ModuleUtils\Exception\AmountMismatchException;
21
use Pagantis\ModuleUtils\Exception\ConcurrencyException;
22
use Pagantis\ModuleUtils\Exception\NoIdentificationException;
23
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
24
use Pagantis\ModuleUtils\Exception\QuoteNotFoundException;
25
use Pagantis\ModuleUtils\Exception\UnknownException;
26
use Pagantis\ModuleUtils\Exception\WrongStatusException;
27
use Pagantis\ModuleUtils\Model\Response\JsonSuccessResponse;
28
use Pagantis\ModuleUtils\Model\Response\JsonExceptionResponse;
29
use Pagantis\ModuleUtils\Exception\AlreadyProcessedException;
30
use Pagantis\ModuleUtils\Model\Log\LogEntry;
31
use Magento\Framework\App\CsrfAwareActionInterface;
32
use Magento\Framework\App\RequestInterface;
33
use Magento\Framework\App\Request\InvalidRequestException;
34
35
/**
36
 * Class Index
37
 * @package Pagantis\Pagantis\Controller\Notify
38
 */
39
class IndexV2 extends Action implements CsrfAwareActionInterface
40
{
41
    /** Orders tablename */
42
    const ORDERS_TABLE = 'cart_process';
43
44
    /** Concurrency tablename */
45
    const CONCURRENCY_TABLE = 'Pagantis_orders';
46
47
    /** Concurrency tablename */
48
    const LOGS_TABLE = 'Pagantis_logs';
49
50
    /** Payment code */
51
    const PAYMENT_METHOD = 'pagantis';
52
53
    /** Seconds to expire a locked request */
54
    const CONCURRENCY_TIMEOUT = 10;
55
56
    /**
57
     * EXCEPTION RESPONSES
58
     */
59
    const CPO_ERR_MSG = 'Order not confirmed';
60
    const CPO_OK_MSG = 'Order confirmed';
61
62
    /** @var QuoteManagement */
63
    protected $quoteManagement;
64
65
    /** @var PaymentInterface $paymentInterface */
66
    protected $paymentInterface;
67
68
    /** @var OrderRepositoryInterface $orderRepositoryInterface */
69
    protected $orderRepositoryInterface;
70
71
    /** @var Quote $quote */
72
    protected $quote;
73
74
    /** @var QuoteRepository $quoteRepository */
75
    protected $quoteRepository;
76
77
    /** @var mixed $config */
78
    protected $config;
79
80
    /** @var mixed $quoteId */
81
    protected $quoteId;
82
83
    /** @var array $notifyResult */
84
    protected $notifyResult;
85
86
    /** @var mixed $magentoOrderId */
87
    protected $magentoOrderId;
88
89
    /** @var mixed $pagantisOrder */
90
    protected $pagantisOrder;
91
92
    /** @var ResourceConnection $dbObject */
93
    protected $dbObject;
94
95
    /** @var Session $checkoutSession */
96
    protected $checkoutSession;
97
98
    /** @var Client $orderClient */
99
    protected $orderClient;
100
101
    /** @var mixed $pagantisOrderId */
102
    protected $pagantisOrderId;
103
104
    /** @var  OrderInterface $magentoOrder */
105
    protected $magentoOrder;
106
107
    /** @var ExtraConfig $extraConfig */
108
    protected $extraConfig;
109
110
    /** @var mixed $origin */
111
    protected $origin;
112
113
    /**
114
     * Index constructor.
115
     *
116
     * @param Context                  $context
117
     * @param Quote                    $quote
118
     * @param QuoteManagement          $quoteManagement
119
     * @param PaymentInterface         $paymentInterface
120
     * @param Config                   $config
121
     * @param QuoteRepository          $quoteRepository
122
     * @param OrderRepositoryInterface $orderRepositoryInterface
123
     * @param ResourceConnection       $dbObject
124
     * @param Session                  $checkoutSession
125
     * @param ExtraConfig              $extraConfig
126
     */
127
    public function __construct(
128
        Context $context,
129
        Quote $quote,
130
        QuoteManagement $quoteManagement,
131
        PaymentInterface $paymentInterface,
132
        Config $config,
133
        QuoteRepository $quoteRepository,
134
        OrderRepositoryInterface $orderRepositoryInterface,
135
        ResourceConnection $dbObject,
136
        Session $checkoutSession,
137
        ExtraConfig $extraConfig
138
    ) {
139
        parent::__construct($context);
140
        $this->quote = $quote;
141
        $this->quoteManagement = $quoteManagement;
142
        $this->paymentInterface = $paymentInterface;
143
        $this->extraConfig = $extraConfig->getExtraConfig();
0 ignored issues
show
Documentation Bug introduced by pgarces
It seems like $extraConfig->getExtraConfig() of type array or array is incompatible with the declared type Pagantis\Pagantis\Helper\ExtraConfig of property $extraConfig.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
144
        $this->config = $config->getConfig();
145
        $this->quoteRepository = $quoteRepository;
146
        $this->orderRepositoryInterface = $orderRepositoryInterface;
147
        $this->dbObject = $dbObject;
148
        $this->checkoutSession = $checkoutSession;
149
        $this->origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notification' : 'Order';
150
    }
151
152
    /**
153
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
154
     * @throws UnknownException
155
     */
156
    public function execute()
157
    {
158
        try {
159
            $this->checkConcurrency();
160
            $this->getMerchantOrder();
161
            $this->getPagantisOrderId();
162
            $this->getPagantisOrder();
163
            $this->checkOrderStatus();
164
            $this->checkMerchantOrderStatus();
165
            $this->validateAmount();
166
            $this->processMerchantOrder();
167
        } catch (\Exception $exception) {
168
            $jsonResponse = new JsonExceptionResponse();
169
            $jsonResponse->setMerchantOrderId($this->magentoOrderId);
170
            $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
171
            $jsonResponse->setException($exception);
172
            $response = $jsonResponse->toJson();
173
            $this->insertLog($exception);
174
        }
175
176
        try {
177
            if (!isset($response)) {
178
                $this->confirmpagantisOrder();
179
                $jsonResponse = new JsonSuccessResponse();
180
                $jsonResponse->setMerchantOrderId($this->magentoOrderId);
181
                $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
182
            }
183
        } catch (\Exception $exception) {
184
            $this->rollbackMerchantOrder();
185
            $jsonResponse = new JsonExceptionResponse();
186
            $jsonResponse->setMerchantOrderId($this->magentoOrderId);
187
            $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
188
            $jsonResponse->setException($exception);
189
            $jsonResponse->toJson();
190
            $this->insertLog($exception);
191
        }
192
193
        $this->unblockConcurrency(true);
194
195
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
196
            $jsonResponse->printResponse();
0 ignored issues
show
Comprehensibility Best Practice introduced by pgarces
The variable $jsonResponse does not seem to be defined for all execution paths leading up to this point.
Loading history...
197
        } else {
198
            $returnUrl = $this->getRedirectUrl();
199
            $this->_redirect($returnUrl);
200
        }
201
    }
202
203
    /**
204
     * COMMON FUNCTIONS
205
     */
206
207
    /**
208
     * @throws ConcurrencyException
209
     * @throws QuoteNotFoundException
210
     * @throws UnknownException
211
     */
212
    private function checkConcurrency()
213
    {
214
        $this->getQuoteId();
215
        $this->checkDbTable();
216
        $this->unblockConcurrency();
217
        $this->blockConcurrency();
218
    }
219
220
    /**
221
     * @throws MerchantOrderNotFoundException
222
     */
223
    private function getMerchantOrder()
224
    {
225
        try {
226
            /** @var Quote quote */
227
            $this->quote = $this->quoteRepository->get($this->quoteId);
228
        } catch (\Exception $e) {
229
            throw new MerchantOrderNotFoundException();
230
        }
231
    }
232
233
    /**
234
     * @throws UnknownException
235
     */
236
    private function getPagantisOrderId()
237
    {
238
        try {
239
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
240
            $dbConnection     = $this->dbObject->getConnection();
241
            $tableName        = $this->dbObject->getTableName(self::ORDERS_TABLE);
242
            $query            = "select order_id from $tableName where id='$this->quoteId'";
243
            $queryResult      = $dbConnection->fetchRow($query);
244
            $this->pagantisOrderId = $queryResult['order_id'];
245
            if ($this->pagantisOrderId == '') {
246
                throw new NoIdentificationException();
247
            }
248
        } catch (\Exception $e) {
249
            throw new UnknownException($e->getMessage());
250
        }
251
    }
252
253
    /**
254
     * @throws OrderNotFoundException
255
     */
256
    private function getPagantisOrder()
257
    {
258
        try {
259
            $this->orderClient = new Client(
260
                $this->config['pagantis_public_key'],
261
                $this->config['pagantis_private_key']
262
            );
263
            $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId);
264
        } catch (\Exception $e) {
265
            throw new OrderNotFoundException();
266
        }
267
    }
268
269
    /**
270
     * @throws AlreadyProcessedException
271
     * @throws WrongStatusException
272
     */
273
    private function checkOrderStatus()
274
    {
275
        try {
276
            $this->checkPagantisStatus(array('AUTHORIZED'));
277
        } catch (\Exception $e) {
278
            $this->getMagentoOrderId();
279
            if ($this->magentoOrderId!='') {
280
                throw new AlreadyProcessedException();
281
            } else {
282
                throw new WrongStatusException($this->pagantisOrder->getStatus());
283
            }
284
        }
285
    }
286
287
    /**
288
     * @throws AlreadyProcessedException
289
     */
290
    private function checkMerchantOrderStatus()
291
    {
292
        if ($this->quote->getIsActive()=='0') {
293
            $this->getMagentoOrderId();
294
            throw new AlreadyProcessedException();
295
        }
296
    }
297
298
    /**
299
     * @throws AmountMismatchException
300
     */
301
    private function validateAmount()
302
    {
303
        $pagantisAmount = $this->pagantisOrder->getShoppingCart()->getTotalAmount();
304
        $merchantAmount = intval(strval(100 * $this->quote->getGrandTotal()));
305
        if ($pagantisAmount != $merchantAmount) {
306
            throw new AmountMismatchException($pagantisAmount, $merchantAmount);
307
        }
308
    }
309
310
    /**
311
     * @throws UnknownException
312
     */
313
    private function processMerchantOrder()
314
    {
315
        try {
316
            $this->saveOrder();
317
            $this->updateBdInfo();
318
        } catch (\Exception $e) {
319
            throw new UnknownException($e->getMessage());
320
        }
321
    }
322
323
    /**
324
     * @return false|string
325
     * @throws UnknownException
326
     */
327
    private function confirmpagantisOrder()
328
    {
329
        try {
330
            $this->pagantisOrder = $this->orderClient->confirmOrder($this->pagantisOrderId);
331
        } catch (\Exception $e) {
332
            throw new UnknownException($e->getMessage());
333
        }
334
335
        $jsonResponse = new JsonSuccessResponse();
336
        $jsonResponse->setStatusCode(200);
337
        $jsonResponse->setMerchantOrderId($this->magentoOrderId);
338
        $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
339
        $jsonResponse->setResult(self::CPO_OK_MSG);
340
        return $jsonResponse->toJson();
341
    }
342
343
    /**
344
     * UTILS FUNCTIONS
345
     */
346
347
    /** STEP 1 CC - Check concurrency
348
     * @throws QuoteNotFoundException
349
     */
350
    private function getQuoteId()
351
    {
352
        $this->quoteId = $this->getRequest()->getParam('quoteId');
353
        if ($this->quoteId == '') {
354
            throw new QuoteNotFoundException();
355
        }
356
    }
357
358
    /**
359
     * @return \Zend_Db_Statement_Interface
360
     * @throws UnknownException
361
     */
362
    private function checkDbTable()
363
    {
364
        try {
365
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
366
            $dbConnection = $this->dbObject->getConnection();
367
            $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
368
            $query = "CREATE TABLE IF NOT EXISTS $tableName(`id` int not null,`timestamp` int not null,PRIMARY KEY (`id`))";
369
370
            return $dbConnection->query($query);
371
        } catch (\Exception $e) {
372
            throw new UnknownException($e->getMessage());
373
        }
374
    }
375
376
    /**
377
     * @return void|\Zend_Db_Statement_Interface
378
     * @throws UnknownException
379
     */
380
    private function checkDbLogTable()
381
    {
382
        try {
383
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
384
            $dbConnection = $this->dbObject->getConnection();
385
            $tableName = $this->dbObject->getTableName(self::LOGS_TABLE);
386
            if (!$dbConnection->isTableExists($tableName)) {
387
                $table = $dbConnection
388
                    ->newTable($tableName)
389
                    ->addColumn(
390
                        'id',
391
                        Table::TYPE_SMALLINT,
392
                        null,
393
                        array('nullable'=>false, 'auto_increment'=>true, 'primary'=>true)
394
                    )
395
                    ->addColumn('log', Table::TYPE_TEXT, null, array('nullable'=>false))
396
                    ->addColumn(
397
                        'createdAt',
398
                        Table::TYPE_TIMESTAMP,
399
                        null,
400
                        array('nullable'=>false, 'default'=>Table::TIMESTAMP_INIT)
401
                    );
402
                return $dbConnection->createTable($table);
403
            }
404
405
            return;
406
        } catch (\Exception $e) {
407
            throw new UnknownException($e->getMessage());
408
        }
409
    }
410
411
    /**
412
     * @param bool $mode
413
     *
414
     * @throws \Exception
415
     */
416
    private function unblockConcurrency($mode = false)
417
    {
418
        try {
419
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
420
            $dbConnection = $this->dbObject->getConnection();
421
            $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
422
            if ($mode == false) {
0 ignored issues
show
Coding Style Best Practice introduced by pgarces
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
423
                $dbConnection->delete($tableName, "timestamp<".(time() - 5));
424
            } elseif ($this->quoteId!='') {
425
                $dbConnection->delete($tableName, "id=".$this->quoteId);
426
            }
427
        } catch (Exception $exception) {
0 ignored issues
show
Bug introduced by pgarces
The type Pagantis\Pagantis\Controller\Notify\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
428
            throw new ConcurrencyException();
429
        }
430
    }
431
432
    /**
433
     * @throws ConcurrencyException
434
     * @throws UnknownException
435
     */
436
    private function blockConcurrency()
437
    {
438
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
439
        $dbConnection = $this->dbObject->getConnection();
440
        $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
441
        $query = "SELECT timestamp FROM $tableName where id='$this->quoteId'";
442
        $resultsSelect = $dbConnection->fetchRow($query);
443
        if (isset($resultsSelect['timestamp'])) {
444
            if ($this->getOrigin() == 'Notification') {
0 ignored issues
show
Bug introduced by pgarces
The method getOrigin() does not exist on Pagantis\Pagantis\Controller\Notify\IndexV2. ( Ignorable by Annotation )

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

444
            if ($this->/** @scrutinizer ignore-call */ getOrigin() == 'Notification') {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
445
                throw new ConcurrencyException();
446
            } else {
447
                $query = sprintf(
448
                    "SELECT timestamp - %s as rest FROM %s %s",
449
                    (time() - self::CONCURRENCY_TIMEOUT),
450
                    $tableName,
451
                    "WHERE id='".$this->quoteId."'"
452
                );
453
                $resultsSelect = $dbConnection->fetchRow($query);
454
                $restSeconds   = isset($resultsSelect['rest']) ? ($resultsSelect['rest']) : 0;
455
                $expirationSec = ($restSeconds > self::CONCURRENCY_TIMEOUT) ? self::CONCURRENCY_TIMEOUT : $restSeconds;
456
                if ($expirationSec > 0) {
457
                    sleep($expirationSec + 1);
458
                }
459
460
                $logMessage  = sprintf(
461
                    "User waiting %s seconds, default seconds %s, bd time to expire %s seconds",
462
                    $expirationSec,
463
                    self::CONCURRENCY_TIMEOUT,
464
                    $restSeconds
465
                );
466
                throw new UnknownException($logMessage);
467
            }
468
        } else {
469
            $dbConnection->insert($tableName, array('id'=>$this->quoteId, 'timestamp'=>time()));
470
        }
471
    }
472
473
    /** STEP 2 GMO - Get Merchant Order */
474
    /** STEP 3 GPOI - Get Pagantis OrderId */
475
    /** STEP 4 GPO - Get Pagantis Order */
476
    /** STEP 5 COS - Check Order Status */
477
    /**
478
     * @param $statusArray
479
     *
480
     * @throws \Exception
481
     */
482
    private function checkPagantisStatus($statusArray)
483
    {
484
        $pagantisStatus = array();
485
        foreach ($statusArray as $status) {
486
            $pagantisStatus[] = constant("\Pagantis\OrdersApiClient\Model\Order::STATUS_$status");
487
        }
488
489
        $payed = in_array($this->pagantisOrder->getStatus(), $pagantisStatus);
490
        if (!$payed) {
491
            throw new WrongStatusException($this->pagantisOrder->getStatus());
492
        }
493
    }
494
495
    /** STEP 6 CMOS - Check Merchant Order Status */
496
    /**
497
     * @throws \Exception
498
     */
499
    private function getMagentoOrderId()
500
    {
501
        try {
502
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
503
            $dbConnection = $this->dbObject->getConnection();
504
            $tableName    = $this->dbObject->getTableName(self::ORDERS_TABLE);
505
            $pagantisOrderId   = $this->pagantisOrderId;
506
            $query        = sprintf(
507
                "select mg_order_id from %s where id='%s' and order_id='%s'",
508
                $tableName,
509
                $this->quoteId,
510
                $pagantisOrderId
511
            );
512
            $queryResult  = $dbConnection->fetchRow($query);
513
            $this->magentoOrderId = $queryResult['mg_order_id'];
514
        } catch (\Exception $e) {
515
            throw new UnknownException($e->getMessage());
516
        }
517
    }
518
519
    /** STEP 7 VA - Validate Amount */
520
    /** STEP 8 PMO - Process Merchant Order */
521
    /**
522
     * @throws UnknownException
523
     */
524
    private function saveOrder()
525
    {
526
        try {
527
            $this->paymentInterface->setMethod(self::PAYMENT_METHOD);
528
            $this->magentoOrderId = $this->quoteManagement->placeOrder($this->quoteId, $this->paymentInterface);
529
            /** @var OrderRepositoryInterface magentoOrder */
530
            $this->magentoOrder = $this->orderRepositoryInterface->get($this->magentoOrderId);
531
            $metadataOrder = $this->pagantisOrder->getMetadata();
532
            $metadataInfo = null;
533
            foreach ($metadataOrder as $metadataKey => $metadataValue) {
534
                if ($metadataKey == 'promotedProduct') {
535
                    $metadataInfo.= "/Producto promocionado = $metadataValue";
536
                }
537
            }
538
539
            $this->magentoOrder->addStatusHistoryComment($metadataInfo)
540
                               ->setIsCustomerNotified(false)
541
                               ->setEntityName('order')
542
                               ->save();
543
544
            $comment = 'pagantisOrderId: ' . $this->pagantisOrder->getId(). ' ' .
545
                       'pagantisOrderStatus: '. $this->pagantisOrder->getStatus(). ' ' .
546
                       'via: '. $this->origin;
547
            $this->magentoOrder->addStatusHistoryComment($comment)
548
                               ->setIsCustomerNotified(false)
549
                               ->setEntityName('order')
550
                               ->save();
551
552
            if ($this->magentoOrderId == '') {
553
                throw new UnknownException('Order can not be saved');
554
            }
555
        } catch (\Exception $e) {
556
            throw new UnknownException($e->getMessage());
557
        }
558
    }
559
560
    /**
561
     * @throws UnknownException
562
     */
563
    private function updateBdInfo()
564
    {
565
        try {
566
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
567
            $dbConnection = $this->dbObject->getConnection();
568
            $tableName    = $this->dbObject->getTableName(self::ORDERS_TABLE);
569
            $pagantisOrderId   = $this->pagantisOrder->getId();
570
            $dbConnection->update(
571
                $tableName,
572
                array('mg_order_id' => $this->magentoOrderId),
573
                "order_id='$pagantisOrderId' and id='$this->quoteId'"
574
            );
575
        } catch (\Exception $e) {
576
            throw new UnknownException($e->getMessage());
577
        }
578
    }
579
580
    /** STEP 9 CPO - Confirmation Pagantis Order */
581
    /**
582
     * @throws UnknownException
583
     */
584
    private function rollbackMerchantOrder()
585
    {
586
        try {
587
            $this->magentoOrder->setState(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT, true);
0 ignored issues
show
Unused Code introduced by pgarces
The call to Magento\Sales\Api\Data\OrderInterface::setState() has too many arguments starting with true. ( Ignorable by Annotation )

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

587
            $this->magentoOrder->/** @scrutinizer ignore-call */ 
588
                                 setState(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT, true);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
588
            $this->magentoOrder->setStatus(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT);
589
            $this->magentoOrder->save();
590
        } catch (\Exception $e) {
591
            throw new UnknownException($e->getMessage());
592
        }
593
    }
594
595
    /**
596
     * @return string
597
     */
598
    private function getRedirectUrl()
599
    {
600
        //$returnUrl = 'checkout/#payment';
601
        $returnUrl = $this->_url->getUrl('checkout', ['_fragment' => 'payment']);
602
        if ($this->magentoOrderId!='') {
603
            /** @var Order $this->magentoOrder */
604
            $this->magentoOrder = $this->orderRepositoryInterface->get($this->magentoOrderId);
605
            if (!$this->_objectManager->get(\Magento\Checkout\Model\Session\SuccessValidator::class)->isValid()) {
606
                $this->checkoutSession
607
                    ->setLastOrderId($this->magentoOrderId)
608
                    ->setLastRealOrderId($this->magentoOrder->getIncrementId())
609
                    ->setLastQuoteId($this->quoteId)
610
                    ->setLastSuccessQuoteId($this->quoteId)
611
                    ->setLastOrderStatus($this->magentoOrder->getStatus());
612
            }
613
614
            //Magento status flow => https://docs.magento.com/m2/ce/user_guide/sales/order-status-workflow.html
615
            //Order Workflow => https://docs.magento.com/m2/ce/user_guide/sales/order-workflow.html
616
            $orderStatus    = strtolower($this->magentoOrder->getStatus());
617
            $acceptedStatus = array('processing', 'completed');
618
            if (in_array($orderStatus, $acceptedStatus)) {
619
                if (isset($this->extraConfig['PAGANTIS_OK_URL']) &&  $this->extraConfig['PAGANTIS_OK_URL']!= '') {
620
                    $returnUrl = $this->extraConfig['PAGANTIS_OK_URL'];
621
                } else {
622
                    $returnUrl = 'checkout/onepage/success';
623
                }
624
            } else {
625
                if (isset($this->extraConfig['PAGANTIS_KO_URL']) && $this->extraConfig['PAGANTIS_KO_URL'] != '') {
626
                    $returnUrl = $this->extraConfig['PAGANTIS_KO_URL'];
627
                } else {
628
                    //$returnUrl = 'checkout/#payment';
629
                    $returnUrl = $this->_url->getUrl('checkout', ['_fragment' => 'payment']);
630
                }
631
            }
632
        }
633
        return $returnUrl;
634
    }
635
636
    /**
637
     * @param $exceptionMessage
638
     *
639
     * @throws UnknownException
640
     */
641
    private function insertLog($exceptionMessage)
642
    {
643
        try {
644
            if ($exceptionMessage instanceof \Exception) {
645
                $this->checkDbLogTable();
646
                $logEntry = new LogEntry();
647
                $logEntryJson = $logEntry->error($exceptionMessage)->toJson();
648
649
                /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
650
                $dbConnection = $this->dbObject->getConnection();
651
                $tableName    = $this->dbObject->getTableName(self::LOGS_TABLE);
652
                $dbConnection->insert($tableName, array('log' => $logEntryJson));
653
            }
654
        } catch (\Exception $e) {
655
            throw new UnknownException($e->getMessage());
656
        }
657
    }
658
659
    /**
660
     * @param RequestInterface $request
661
     *
662
     * @return InvalidRequestException|null
663
     */
664
    public function createCsrfValidationException(RequestInterface $request): ? InvalidRequestException
665
    {
666
        return null;
667
    }
668
669
    /**
670
     * @param RequestInterface $request
671
     *
672
     * @return bool|null
673
     */
674
    public function validateForCsrf(RequestInterface $request): ? bool
675
    {
676
        return true;
677
    }
678
}
679