Completed
Push — master ( 08c5b9...8b6449 )
by pablo
15s queued 11s
created

IndexV2::getOrigin()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
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\RequestInterface;
32
use Magento\Framework\App\Request\InvalidRequestException;
33
34
/**
35
 * Class Index
36
 * @package Pagantis\Pagantis\Controller\Notify
37
 */
38
class IndexV2 extends Action
39
{
40
    /** Orders tablename */
41
    const ORDERS_TABLE = 'cart_process';
42
43
    /** Concurrency tablename */
44
    const CONCURRENCY_TABLE = 'Pagantis_orders';
45
46
    /** Concurrency tablename */
47
    const LOGS_TABLE = 'Pagantis_logs';
48
49
    /** Payment code */
50
    const PAYMENT_METHOD = 'pagantis';
51
52
    /** Seconds to expire a locked request */
53
    const CONCURRENCY_TIMEOUT = 10;
54
55
    /**
56
     * EXCEPTION RESPONSES
57
     */
58
    const CPO_ERR_MSG = 'Order not confirmed';
59
    const CPO_OK_MSG = 'Order confirmed';
60
61
    /** @var QuoteManagement */
62
    protected $quoteManagement;
63
64
    /** @var PaymentInterface $paymentInterface */
65
    protected $paymentInterface;
66
67
    /** @var OrderRepositoryInterface $orderRepositoryInterface */
68
    protected $orderRepositoryInterface;
69
70
    /** @var Quote $quote */
71
    protected $quote;
72
73
    /** @var QuoteRepository $quoteRepository */
74
    protected $quoteRepository;
75
76
    /** @var mixed $config */
77
    protected $config;
78
79
    /** @var mixed $quoteId */
80
    protected $quoteId;
81
82
    /** @var array $notifyResult */
83
    protected $notifyResult;
84
85
    /** @var mixed $magentoOrderId */
86
    protected $magentoOrderId;
87
88
    /** @var mixed $pagantisOrder */
89
    protected $pagantisOrder;
90
91
    /** @var ResourceConnection $dbObject */
92
    protected $dbObject;
93
94
    /** @var Session $checkoutSession */
95
    protected $checkoutSession;
96
97
    /** @var Client $orderClient */
98
    protected $orderClient;
99
100
    /** @var mixed $pagantisOrderId */
101
    protected $pagantisOrderId;
102
103
    /** @var  OrderInterface $magentoOrder */
104
    protected $magentoOrder;
105
106
    /** @var ExtraConfig $extraConfig */
107
    protected $extraConfig;
108
109
    /** @var mixed $origin */
110
    protected $origin;
111
112
    /**
113
     * IndexV2 constructor.
114
     *
115
     * @param Context                  $context
116
     * @param Quote                    $quote
117
     * @param QuoteManagement          $quoteManagement
118
     * @param PaymentInterface         $paymentInterface
119
     * @param Config                   $config
120
     * @param QuoteRepository          $quoteRepository
121
     * @param OrderRepositoryInterface $orderRepositoryInterface
122
     * @param ResourceConnection       $dbObject
123
     * @param Session                  $checkoutSession
124
     * @param ExtraConfig              $extraConfig
125
     * @param RequestInterface         $request
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
        RequestInterface $request
139
    ) {
140
        parent::__construct($context);
141
142
        $this->quote = $quote;
143
        $this->quoteManagement = $quoteManagement;
144
        $this->paymentInterface = $paymentInterface;
145
        $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...
146
        $this->config = $config->getConfig();
147
        $this->quoteRepository = $quoteRepository;
148
        $this->orderRepositoryInterface = $orderRepositoryInterface;
149
        $this->dbObject = $dbObject;
150
        $this->checkoutSession = $checkoutSession;
151
        $this->origin = ($_SERVER['REQUEST_METHOD'] == 'POST') ? 'Notification' : 'Order';
152
153
        // CsrfAwareAction Magento2.3 compatibility
154
        if (interface_exists("\Magento\Framework\App\CsrfAwareActionInterface")) {
155
            if (isset($request) && $request->isPost() && empty($request->getParam('form_key'))) {
0 ignored issues
show
Bug introduced by pgarces
The method isPost() does not exist on Magento\Framework\App\RequestInterface. It seems like you code against a sub-type of Magento\Framework\App\RequestInterface such as Magento\Framework\Webapi\Request or Magento\Framework\App\Request\Http. ( Ignorable by Annotation )

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

155
            if (isset($request) && $request->/** @scrutinizer ignore-call */ isPost() && empty($request->getParam('form_key'))) {
Loading history...
156
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
157
                $formKey = $objectManager->get(\Magento\Framework\Data\Form\FormKey::class);
158
                $request->setParam('form_key', $formKey->getFormKey());
0 ignored issues
show
Bug introduced by pgarces
The method setParam() does not exist on Magento\Framework\App\RequestInterface. Did you maybe mean setParams()? ( Ignorable by Annotation )

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

158
                $request->/** @scrutinizer ignore-call */ 
159
                          setParam('form_key', $formKey->getFormKey());

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...
159
            }
160
        }
161
    }
162
163
    /**
164
     * @return \Magento\Framework\App\ResponseInterface|\Magento\Framework\Controller\ResultInterface|void
165
     * @throws UnknownException
166
     */
167
    public function execute()
168
    {
169
        try {
170
            if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_GET['origin'] == 'notification') {
171
                $returnUrl = $this->_url->getUrl('checkout', ['_fragment' => 'payment']);
172
                $this->_redirect($returnUrl);
173
            }
174
            $this->checkConcurrency();
175
            $this->getMerchantOrder();
176
            $this->getPagantisOrderId();
177
            $this->getPagantisOrder();
178
            $this->checkOrderStatus();
179
            $this->checkMerchantOrderStatus();
180
            $this->validateAmount();
181
            $this->processMerchantOrder();
182
        } catch (\Exception $exception) {
183
            $jsonResponse = new JsonExceptionResponse();
184
            $jsonResponse->setMerchantOrderId($this->magentoOrderId);
185
            $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
186
            $jsonResponse->setException($exception);
187
            $response = $jsonResponse->toJson();
188
            $this->insertLog($exception);
189
        }
190
191
        try {
192
            if (!isset($response)) {
193
                $this->confirmpagantisOrder();
194
                $jsonResponse = new JsonSuccessResponse();
195
                $jsonResponse->setMerchantOrderId($this->magentoOrderId);
196
                $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
197
            }
198
        } catch (\Exception $exception) {
199
            $this->rollbackMerchantOrder();
200
            $jsonResponse = new JsonExceptionResponse();
201
            $jsonResponse->setMerchantOrderId($this->magentoOrderId);
202
            $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
203
            $jsonResponse->setException($exception);
204
            $jsonResponse->toJson();
205
            $this->insertLog($exception);
206
        }
207
208
        $this->unblockConcurrency(true);
209
210
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
211
            $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...
212
        } else {
213
            $returnUrl = $this->getRedirectUrl();
214
            $this->_redirect($returnUrl);
215
        }
216
    }
217
218
    /**
219
     * COMMON FUNCTIONS
220
     */
221
222
    /**
223
     * @throws ConcurrencyException
224
     * @throws QuoteNotFoundException
225
     * @throws UnknownException
226
     */
227
    private function checkConcurrency()
228
    {
229
        $this->getQuoteId();
230
        $this->checkDbTable();
231
        $this->unblockConcurrency();
232
        $this->blockConcurrency();
233
    }
234
235
    /**
236
     * @throws MerchantOrderNotFoundException
237
     */
238
    private function getMerchantOrder()
239
    {
240
        try {
241
            /** @var Quote quote */
242
            $this->quote = $this->quoteRepository->get($this->quoteId);
243
        } catch (\Exception $e) {
244
            throw new MerchantOrderNotFoundException();
245
        }
246
    }
247
248
    /**
249
     * @throws UnknownException
250
     */
251
    private function getPagantisOrderId()
252
    {
253
        try {
254
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
255
            $dbConnection     = $this->dbObject->getConnection();
256
            $tableName        = $this->dbObject->getTableName(self::ORDERS_TABLE);
257
            $query            = "select order_id from $tableName where id='$this->quoteId'";
258
            $queryResult      = $dbConnection->fetchRow($query);
259
            $this->pagantisOrderId = $queryResult['order_id'];
260
            if ($this->pagantisOrderId == '') {
261
                throw new NoIdentificationException();
262
            }
263
        } catch (\Exception $e) {
264
            throw new UnknownException($e->getMessage());
265
        }
266
    }
267
268
    /**
269
     * @throws OrderNotFoundException
270
     */
271
    private function getPagantisOrder()
272
    {
273
        try {
274
            $this->orderClient = new Client(
275
                $this->config['pagantis_public_key'],
276
                $this->config['pagantis_private_key']
277
            );
278
            $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId);
279
        } catch (\Exception $e) {
280
            throw new OrderNotFoundException();
281
        }
282
    }
283
284
    /**
285
     * @throws AlreadyProcessedException
286
     * @throws WrongStatusException
287
     */
288
    private function checkOrderStatus()
289
    {
290
        try {
291
            $this->checkPagantisStatus(array('AUTHORIZED'));
292
        } catch (\Exception $e) {
293
            $this->getMagentoOrderId();
294
            if ($this->magentoOrderId!='') {
295
                throw new AlreadyProcessedException();
296
            } else {
297
                throw new WrongStatusException($this->pagantisOrder->getStatus());
298
            }
299
        }
300
    }
301
302
    /**
303
     * @throws AlreadyProcessedException
304
     */
305
    private function checkMerchantOrderStatus()
306
    {
307
        if ($this->quote->getIsActive()=='0') {
308
            $this->getMagentoOrderId();
309
            throw new AlreadyProcessedException();
310
        }
311
    }
312
313
    /**
314
     * @throws AmountMismatchException
315
     */
316
    private function validateAmount()
317
    {
318
        $pagantisAmount = $this->pagantisOrder->getShoppingCart()->getTotalAmount();
319
        $merchantAmount = intval(strval(100 * $this->quote->getGrandTotal()));
320
        if ($pagantisAmount != $merchantAmount) {
321
            throw new AmountMismatchException($pagantisAmount, $merchantAmount);
322
        }
323
    }
324
325
    /**
326
     * @throws UnknownException
327
     */
328
    private function processMerchantOrder()
329
    {
330
        try {
331
            $this->saveOrder();
332
            $this->updateBdInfo();
333
        } catch (\Exception $e) {
334
            throw new UnknownException($e->getMessage());
335
        }
336
    }
337
338
    /**
339
     * @return false|string
340
     * @throws UnknownException
341
     */
342
    private function confirmpagantisOrder()
343
    {
344
        try {
345
            $this->pagantisOrder = $this->orderClient->confirmOrder($this->pagantisOrderId);
346
        } catch (\Exception $e) {
347
            throw new UnknownException($e->getMessage());
348
        }
349
350
        $jsonResponse = new JsonSuccessResponse();
351
        $jsonResponse->setStatusCode(200);
352
        $jsonResponse->setMerchantOrderId($this->magentoOrderId);
353
        $jsonResponse->setpagantisOrderId($this->pagantisOrderId);
354
        $jsonResponse->setResult(self::CPO_OK_MSG);
355
        return $jsonResponse->toJson();
356
    }
357
358
    /**
359
     * UTILS FUNCTIONS
360
     */
361
362
    /** STEP 1 CC - Check concurrency
363
     * @throws QuoteNotFoundException
364
     */
365
    private function getQuoteId()
366
    {
367
        $this->quoteId = $this->getRequest()->getParam('quoteId');
368
        if ($this->quoteId == '') {
369
            throw new QuoteNotFoundException();
370
        }
371
    }
372
373
    /**
374
     * @return \Zend_Db_Statement_Interface
375
     * @throws UnknownException
376
     */
377
    private function checkDbTable()
378
    {
379
        try {
380
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
381
            $dbConnection = $this->dbObject->getConnection();
382
            $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
383
            $query = "CREATE TABLE IF NOT EXISTS $tableName(`id` int not null,`timestamp` int not null,PRIMARY KEY (`id`))";
384
385
            return $dbConnection->query($query);
386
        } catch (\Exception $e) {
387
            throw new UnknownException($e->getMessage());
388
        }
389
    }
390
391
    /**
392
     * @return void|\Zend_Db_Statement_Interface
393
     * @throws UnknownException
394
     */
395
    private function checkDbLogTable()
396
    {
397
        try {
398
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
399
            $dbConnection = $this->dbObject->getConnection();
400
            $tableName = $this->dbObject->getTableName(self::LOGS_TABLE);
401
            if (!$dbConnection->isTableExists($tableName)) {
402
                $table = $dbConnection
403
                    ->newTable($tableName)
404
                    ->addColumn(
405
                        'id',
406
                        Table::TYPE_SMALLINT,
407
                        null,
408
                        array('nullable'=>false, 'auto_increment'=>true, 'primary'=>true)
409
                    )
410
                    ->addColumn('log', Table::TYPE_TEXT, null, array('nullable'=>false))
411
                    ->addColumn(
412
                        'createdAt',
413
                        Table::TYPE_TIMESTAMP,
414
                        null,
415
                        array('nullable'=>false, 'default'=>Table::TIMESTAMP_INIT)
416
                    );
417
                return $dbConnection->createTable($table);
418
            }
419
420
            return;
421
        } catch (\Exception $e) {
422
            throw new UnknownException($e->getMessage());
423
        }
424
    }
425
426
    /**
427
     * @param bool $mode
428
     *
429
     * @throws \Exception
430
     */
431
    private function unblockConcurrency($mode = false)
432
    {
433
        try {
434
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
435
            $dbConnection = $this->dbObject->getConnection();
436
            $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
437
            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...
438
                $dbConnection->delete($tableName, "timestamp<".(time() - 5));
439
            } elseif ($this->quoteId!='') {
440
                $dbConnection->delete($tableName, "id=".$this->quoteId);
441
            }
442
        } 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...
443
            throw new ConcurrencyException();
444
        }
445
    }
446
447
    /**
448
     * @throws ConcurrencyException
449
     * @throws UnknownException
450
     */
451
    private function blockConcurrency()
452
    {
453
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
454
        $dbConnection = $this->dbObject->getConnection();
455
        $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
456
        $query = "SELECT timestamp FROM $tableName where id='$this->quoteId'";
457
        $resultsSelect = $dbConnection->fetchRow($query);
458
        if (isset($resultsSelect['timestamp'])) {
459
            if ($this->getOrigin() == 'Notification') {
460
                throw new ConcurrencyException();
461
            } else {
462
                $query = sprintf(
463
                    "SELECT timestamp - %s as rest FROM %s %s",
464
                    (time() - self::CONCURRENCY_TIMEOUT),
465
                    $tableName,
466
                    "WHERE id='".$this->quoteId."'"
467
                );
468
                $resultsSelect = $dbConnection->fetchRow($query);
469
                $restSeconds   = isset($resultsSelect['rest']) ? ($resultsSelect['rest']) : 0;
470
                $expirationSec = ($restSeconds > self::CONCURRENCY_TIMEOUT) ? self::CONCURRENCY_TIMEOUT : $restSeconds;
471
                if ($expirationSec > 0) {
472
                    sleep($expirationSec + 1);
473
                }
474
475
                $logMessage  = sprintf(
476
                    "User waiting %s seconds, default seconds %s, bd time to expire %s seconds",
477
                    $expirationSec,
478
                    self::CONCURRENCY_TIMEOUT,
479
                    $restSeconds
480
                );
481
                throw new UnknownException($logMessage);
482
            }
483
        } else {
484
            $dbConnection->insert($tableName, array('id'=>$this->quoteId, 'timestamp'=>time()));
485
        }
486
    }
487
488
    /** STEP 2 GMO - Get Merchant Order */
489
    /** STEP 3 GPOI - Get Pagantis OrderId */
490
    /** STEP 4 GPO - Get Pagantis Order */
491
    /** STEP 5 COS - Check Order Status */
492
    /**
493
     * @param $statusArray
494
     *
495
     * @throws \Exception
496
     */
497
    private function checkPagantisStatus($statusArray)
498
    {
499
        $pagantisStatus = array();
500
        foreach ($statusArray as $status) {
501
            $pagantisStatus[] = constant("\Pagantis\OrdersApiClient\Model\Order::STATUS_$status");
502
        }
503
504
        $payed = in_array($this->pagantisOrder->getStatus(), $pagantisStatus);
505
        if (!$payed) {
506
            throw new WrongStatusException($this->pagantisOrder->getStatus());
507
        }
508
    }
509
510
    /** STEP 6 CMOS - Check Merchant Order Status */
511
    /**
512
     * @throws \Exception
513
     */
514
    private function getMagentoOrderId()
515
    {
516
        try {
517
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
518
            $dbConnection = $this->dbObject->getConnection();
519
            $tableName    = $this->dbObject->getTableName(self::ORDERS_TABLE);
520
            $pagantisOrderId   = $this->pagantisOrderId;
521
            $query        = sprintf(
522
                "select mg_order_id from %s where id='%s' and order_id='%s'",
523
                $tableName,
524
                $this->quoteId,
525
                $pagantisOrderId
526
            );
527
            $queryResult  = $dbConnection->fetchRow($query);
528
            $this->magentoOrderId = $queryResult['mg_order_id'];
529
        } catch (\Exception $e) {
530
            throw new UnknownException($e->getMessage());
531
        }
532
    }
533
534
    /** STEP 7 VA - Validate Amount */
535
    /** STEP 8 PMO - Process Merchant Order */
536
    /**
537
     * @throws UnknownException
538
     */
539
    private function saveOrder()
540
    {
541
        try {
542
            $this->paymentInterface->setMethod(self::PAYMENT_METHOD);
543
            $this->magentoOrderId = $this->quoteManagement->placeOrder($this->quoteId, $this->paymentInterface);
544
            /** @var OrderRepositoryInterface magentoOrder */
545
            $this->magentoOrder = $this->orderRepositoryInterface->get($this->magentoOrderId);
546
            $metadataOrder = $this->pagantisOrder->getMetadata();
547
            $metadataInfo = null;
548
            foreach ($metadataOrder as $metadataKey => $metadataValue) {
549
                if ($metadataKey == 'promotedProduct') {
550
                    $metadataInfo.= "/Producto promocionado = $metadataValue";
551
                }
552
            }
553
554
            $this->magentoOrder->addStatusHistoryComment($metadataInfo)
555
                               ->setIsCustomerNotified(false)
556
                               ->setEntityName('order')
557
                               ->save();
558
559
            $comment = 'pagantisOrderId: ' . $this->pagantisOrder->getId(). ' ' .
560
                       'pagantisOrderStatus: '. $this->pagantisOrder->getStatus(). ' ' .
561
                       'via: '. $this->origin;
562
            $this->magentoOrder->addStatusHistoryComment($comment)
563
                               ->setIsCustomerNotified(false)
564
                               ->setEntityName('order')
565
                               ->save();
566
567
            if ($this->magentoOrderId == '') {
568
                throw new UnknownException('Order can not be saved');
569
            }
570
        } catch (\Exception $e) {
571
            throw new UnknownException($e->getMessage());
572
        }
573
    }
574
575
    /**
576
     * @throws UnknownException
577
     */
578
    private function updateBdInfo()
579
    {
580
        try {
581
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
582
            $dbConnection = $this->dbObject->getConnection();
583
            $tableName    = $this->dbObject->getTableName(self::ORDERS_TABLE);
584
            $pagantisOrderId   = $this->pagantisOrder->getId();
585
            $dbConnection->update(
586
                $tableName,
587
                array('mg_order_id' => $this->magentoOrderId),
588
                "order_id='$pagantisOrderId' and id='$this->quoteId'"
589
            );
590
        } catch (\Exception $e) {
591
            throw new UnknownException($e->getMessage());
592
        }
593
    }
594
595
    /** STEP 9 CPO - Confirmation Pagantis Order */
596
    /**
597
     * @throws UnknownException
598
     */
599
    private function rollbackMerchantOrder()
600
    {
601
        try {
602
            $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

602
            $this->magentoOrder->/** @scrutinizer ignore-call */ 
603
                                 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...
603
            $this->magentoOrder->setStatus(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT);
604
            $this->magentoOrder->save();
605
        } catch (\Exception $e) {
606
            throw new UnknownException($e->getMessage());
607
        }
608
    }
609
610
    /**
611
     * @return mixed
612
     */
613
    public function getOrigin()
614
    {
615
        return $this->origin;
616
    }
617
618
    /**
619
     * @param mixed $origin
620
     */
621
    public function setOrigin($origin)
622
    {
623
        $this->origin = $origin;
624
    }
625
626
    /**
627
     * @return string
628
     */
629
    private function getRedirectUrl()
630
    {
631
        //$returnUrl = 'checkout/#payment';
632
        $returnUrl = $this->_url->getUrl('checkout', ['_fragment' => 'payment']);
633
        if ($this->magentoOrderId!='') {
634
            /** @var Order $this->magentoOrder */
635
            $this->magentoOrder = $this->orderRepositoryInterface->get($this->magentoOrderId);
636
            if (!$this->_objectManager->get(\Magento\Checkout\Model\Session\SuccessValidator::class)->isValid()) {
637
                $this->checkoutSession
638
                    ->setLastOrderId($this->magentoOrderId)
639
                    ->setLastRealOrderId($this->magentoOrder->getIncrementId())
640
                    ->setLastQuoteId($this->quoteId)
641
                    ->setLastSuccessQuoteId($this->quoteId)
642
                    ->setLastOrderStatus($this->magentoOrder->getStatus());
643
            }
644
645
            //Magento status flow => https://docs.magento.com/m2/ce/user_guide/sales/order-status-workflow.html
646
            //Order Workflow => https://docs.magento.com/m2/ce/user_guide/sales/order-workflow.html
647
            $orderStatus    = strtolower($this->magentoOrder->getStatus());
648
            $acceptedStatus = array('processing', 'completed');
649
            if (in_array($orderStatus, $acceptedStatus)) {
650
                if (isset($this->extraConfig['PAGANTIS_OK_URL']) &&  $this->extraConfig['PAGANTIS_OK_URL']!= '') {
651
                    $returnUrl = $this->extraConfig['PAGANTIS_OK_URL'];
652
                } else {
653
                    $returnUrl = 'checkout/onepage/success';
654
                }
655
            } else {
656
                if (isset($this->extraConfig['PAGANTIS_KO_URL']) && $this->extraConfig['PAGANTIS_KO_URL'] != '') {
657
                    $returnUrl = $this->extraConfig['PAGANTIS_KO_URL'];
658
                } else {
659
                    //$returnUrl = 'checkout/#payment';
660
                    $returnUrl = $this->_url->getUrl('checkout', ['_fragment' => 'payment']);
661
                }
662
            }
663
        }
664
        return $returnUrl;
665
    }
666
667
    /**
668
     * @param $exceptionMessage
669
     *
670
     * @throws UnknownException
671
     */
672
    private function insertLog($exceptionMessage)
673
    {
674
        try {
675
            if ($exceptionMessage instanceof \Exception) {
676
                $this->checkDbLogTable();
677
                $logEntry = new LogEntry();
678
                $logEntryJson = $logEntry->error($exceptionMessage)->toJson();
679
680
                /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
681
                $dbConnection = $this->dbObject->getConnection();
682
                $tableName    = $this->dbObject->getTableName(self::LOGS_TABLE);
683
                $dbConnection->insert($tableName, array('log' => $logEntryJson));
684
            }
685
        } catch (\Exception $e) {
686
            throw new UnknownException($e->getMessage());
687
        }
688
    }
689
690
    /**
691
     * @param RequestInterface $request
692
     *
693
     * @return InvalidRequestException|null
694
     */
695
    public function createCsrfValidationException(RequestInterface $request): ? InvalidRequestException
0 ignored issues
show
Unused Code introduced by pgarces
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

695
    public function createCsrfValidationException(/** @scrutinizer ignore-unused */ RequestInterface $request): ? InvalidRequestException

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
696
    {
697
        return null;
698
    }
699
700
    /**
701
     * @param RequestInterface $request
702
     *
703
     * @return bool|null
704
     */
705
    public function validateForCsrf(RequestInterface $request): ? bool
0 ignored issues
show
Unused Code introduced by pgarces
The parameter $request is not used and could be removed. ( Ignorable by Annotation )

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

705
    public function validateForCsrf(/** @scrutinizer ignore-unused */ RequestInterface $request): ? bool

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
706
    {
707
        return true;
708
    }
709
}
710