Completed
Push — master ( 9a394c...0861ee )
by
unknown
01:32 queued 01:11
created

Index::checkPmtStatus()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 4
nop 1
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace DigitalOrigin\Pmt\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 PagaMasTarde\OrdersApiClient\Client;
14
use DigitalOrigin\Pmt\Helper\Config;
15
use Magento\Framework\App\ResourceConnection;
16
use Magento\Checkout\Model\Session;
17
use Magento\Framework\DB\Ddl\Table;
18
19
/**
20
 * Class Index
21
 * @package DigitalOrigin\Pmt\Controller\Notify
22
 */
23
class Index extends Action
24
{
25
    /** Orders tablename */
26
    const ORDERS_TABLE = 'cart_process';
27
28
    /** Concurrency tablename */
29
    const CONCURRENCY_TABLE = 'pmt_orders';
30
31
    /** Concurrency tablename */
32
    const LOGS_TABLE = 'pmt_logs';
33
34
    /** Payment code */
35
    const PAYMENT_METHOD = 'paylater';
36
37
    /**
38
     * EXCEPTION RESPONSES
39
     */
40
    const CC_ERR_MSG = 'Unable to block resource';
41
    const CC_NO_QUOTE = 'QuoteId not found';
42
    const CC_NO_VALIDATE ='Validation in progress, try again later';
43
    const GMO_ERR_MSG = 'Merchant Order Not Found';
44
    const GPOI_ERR_MSG = 'Pmt Order Not Found';
45
    const GPOI_NO_ORDERID = 'We can not get the PagaMasTarde identification in database.';
46
    const GPO_ERR_MSG = 'Unable to get Order';
47
    const COS_ERR_MSG = 'Order status is not authorized';
48
    const COS_WRONG_STATUS = 'Invalid Pmt status';
49
    const CMOS_ERR_MSG = 'Merchant Order status is invalid';
50
    const CMOS_ALREADY_PROCESSED = 'Cart already processed.';
51
    const VA_ERR_MSG = 'Amount conciliation error';
52
    const VA_WRONG_AMOUNT = 'Wrong order amount';
53
    const PMO_ERR_MSG = 'Unknown Error';
54
    const CPO_ERR_MSG = 'Order not confirmed';
55
    const CPO_OK_MSG = 'Order confirmed';
56
57
    /** @var QuoteManagement */
58
    protected $quoteManagement;
59
60
    /** @var PaymentInterface $paymentInterface */
61
    protected $paymentInterface;
62
63
    /** @var OrderRepositoryInterface $orderRepositoryInterface */
64
    protected $orderRepositoryInterface;
65
66
    /** @var Quote $quote */
67
    protected $quote;
68
69
    /** @var QuoteRepository $quoteRepository */
70
    protected $quoteRepository;
71
72
    /** @var mixed $config */
73
    protected $config;
74
75
    /** @var mixed $quoteId */
76
    protected $quoteId;
77
78
    /** @var Array_ $notifyResult */
0 ignored issues
show
Bug introduced by
The type DigitalOrigin\Pmt\Controller\Notify\Array_ 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...
79
    protected $notifyResult;
80
81
    /** @var mixed $magentoOrderId */
82
    protected $magentoOrderId;
83
84
    /** @var mixed $pmtOrder */
85
    protected $pmtOrder;
86
87
    /** @var ResourceConnection $dbObject */
88
    protected $dbObject;
89
90
    /** @var Session $checkoutSession */
91
    protected $checkoutSession;
92
93
    /** @var Client $orderClient */
94
    protected $orderClient;
95
96
    /** @var mixed $pmtOrderId */
97
    protected $pmtOrderId;
98
99
    /** @var  OrderInterface $magentoOrder */
100
    protected $magentoOrder;
101
102
    /**
103
     * Index constructor.
104
     *
105
     * @param Context                  $context
106
     * @param Quote                    $quote
107
     * @param QuoteManagement          $quoteManagement
108
     * @param PaymentInterface         $paymentInterface
109
     * @param Config                   $config
110
     * @param QuoteRepository          $quoteRepository
111
     * @param OrderRepositoryInterface $orderRepositoryInterface
112
     * @param ResourceConnection       $dbObject
113
     * @param Session                  $checkoutSession
114
     */
115
    public function __construct(
116
        Context $context,
117
        Quote $quote,
118
        QuoteManagement $quoteManagement,
119
        PaymentInterface $paymentInterface,
120
        Config $config,
121
        QuoteRepository $quoteRepository,
122
        OrderRepositoryInterface $orderRepositoryInterface,
123
        ResourceConnection $dbObject,
124
        Session $checkoutSession
125
    ) {
126
        parent::__construct($context);
127
        $this->quote = $quote;
128
        $this->quoteManagement = $quoteManagement;
129
        $this->paymentInterface = $paymentInterface;
130
        $this->config = $config->getConfig();
131
        $this->quoteRepository = $quoteRepository;
132
        $this->orderRepositoryInterface = $orderRepositoryInterface;
133
        $this->dbObject = $dbObject;
134
        $this->checkoutSession = $checkoutSession;
135
    }
136
137
    //MAIN FUNCTION
138
    public function execute()
139
    {
140
        try {
141
            $this->checkConcurrency();
142
            $this->getMerchantOrder();
143
            $this->getPmtOrderId();
144
            $this->getPmtOrder();
145
            $this->checkOrderStatus();
146
            $this->checkMerchantOrderStatus();
147
            $this->validateAmount();
148
            $this->processMerchantOrder();
149
        } catch (\Exception $exception) {
150
            $this->insertLog($exception);
151
            $exception = unserialize($exception->getMessage());
152
            $status = $exception->status;
153
            $response = array();
154
            $response['timestamp'] = time();
155
            $response['order_id']= $this->magentoOrderId;
156
            $response['result'] = $exception->result;
157
            $response['result_description'] = $exception->result_description;
158
            $response = json_encode($response);
159
        }
160
161
        try {
162
            if (!isset($response)) {
163
                $response = $this->confirmPmtOrder();
164
            }
165
        } catch (\Exception $exception) {
166
            $this->insertLog($exception);
167
            $this->rollbackMerchantOrder();
168
            $exception = unserialize($exception->getMessage());
169
            $status = $exception->status;
170
            $response = array();
171
            $response['timestamp'] = time();
172
            $response['order_id']= $this->magentoOrderId;
173
            $response['result'] = self::CPO_ERR_MSG;
174
            $response['result_description'] = $exception->result_description;
175
            $response = json_encode($response);
176
        }
177
178
        $this->unblockConcurrency(true);
179
180
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
181
            header("HTTP/1.1 $status", true, $status);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $status does not seem to be defined for all execution paths leading up to this point.
Loading history...
182
            header('Content-Type: application/json', true);
183
            header('Content-Length: ' . strlen($response));
184
            echo ($response);
185
            exit();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
186
        } else {
187
            $returnUrl = $this->getRedirectUrl();
188
            $this->_redirect($returnUrl);
189
        }
190
    }
191
192
    /**
193
     * COMMON FUNCTIONS
194
     */
195
196
    private function checkConcurrency()
197
    {
198
        try {
199
            $this->getQuoteId();
200
            $this->checkDbTable();
201
            $this->unblockConcurrency();
202
            $this->blockConcurrency();
203
        } catch (\Exception $e) {
204
            $exceptionObject = new \stdClass();
205
            $exceptionObject->method= __FUNCTION__;
206
            $exceptionObject->status='429';
207
            $exceptionObject->result= self::CC_ERR_MSG;
208
            $exceptionObject->result_description = $e->getMessage();
209
            throw new \Exception(serialize($exceptionObject));
210
        }
211
    }
212
213
    private function getMerchantOrder()
214
    {
215
        try {
216
            $this->quote = $this->quoteRepository->get($this->quoteId);
217
        } catch (\Exception $e) {
218
            $exceptionObject = new \stdClass();
219
            $exceptionObject->method= __FUNCTION__;
220
            $exceptionObject->status='404';
221
            $exceptionObject->result= self::GMO_ERR_MSG;
222
            $exceptionObject->result_description = $e->getMessage();
223
            throw new \Exception(serialize($exceptionObject));
224
        }
225
    }
226
227
    private function getPmtOrderId()
228
    {
229
        try {
230
            $this->getPmtOrderIdDb();
231
        } catch (\Exception $e) {
232
            $exceptionObject = new \stdClass();
233
            $exceptionObject->method= __FUNCTION__;
234
            $exceptionObject->status='404';
235
            $exceptionObject->result= self::GPOI_ERR_MSG;
236
            $exceptionObject->result_description = $e->getMessage();
237
            throw new \Exception(serialize($exceptionObject));
238
        }
239
    }
240
241
    private function getPmtOrder()
242
    {
243
        try {
244
            $this->orderClient = new Client($this->config['public_key'], $this->config['secret_key']);
245
            $this->pmtOrder = $this->orderClient->getOrder($this->pmtOrderId);
246
        } catch (\Exception $e) {
247
            $exceptionObject = new \stdClass();
248
            $exceptionObject->method= __FUNCTION__;
249
            $exceptionObject->status='400';
250
            $exceptionObject->result= self::GPO_ERR_MSG;
251
            $exceptionObject->result_description = $e->getMessage();
252
            throw new \Exception(serialize($exceptionObject));
253
        }
254
    }
255
256
    private function checkOrderStatus()
257
    {
258
        try {
259
            $this->checkPmtStatus(array('AUTHORIZED'));
260
        } catch (\Exception $e) {
261
            $this->getMagentoOrderId();
262
            $exceptionObject = new \stdClass();
263
            $exceptionObject->method= __FUNCTION__;
264
            if ($this->magentoOrderId!='') {
265
                $exceptionObject->status='200';
266
                $exceptionObject->result= self::CMOS_ALREADY_PROCESSED;
267
                $exceptionObject->result_description = self::CMOS_ALREADY_PROCESSED;
268
            } else {
269
                $exceptionObject->status='403';
270
                $exceptionObject->result= self::COS_ERR_MSG;
271
                $exceptionObject->result_description = $e->getMessage();
272
            }
273
            throw new \Exception(serialize($exceptionObject));
274
        }
275
    }
276
277
    private function checkMerchantOrderStatus()
278
    {
279
        try {
280
            $this->checkCartStatus();
281
        } catch (\Exception $e) {
282
            $exceptionObject = new \stdClass();
283
            $exceptionObject->method= __FUNCTION__;
284
            $exceptionObject->status='409';
285
            $exceptionObject->result= self::CMOS_ERR_MSG;
286
            $exceptionObject->result_description = $e->getMessage();
287
            throw new \Exception(serialize($exceptionObject));
288
        }
289
    }
290
291
    private function validateAmount()
292
    {
293
        try {
294
            $this->comparePrices();
295
        } catch (\Exception $e) {
296
            $exceptionObject = new \stdClass();
297
            $exceptionObject->method= __FUNCTION__;
298
            $exceptionObject->status='409';
299
            $exceptionObject->result= self::VA_ERR_MSG;
300
            $exceptionObject->result_description = $e->getMessage();
301
            throw new \Exception(serialize($exceptionObject));
302
        }
303
    }
304
305
    private function processMerchantOrder()
306
    {
307
        try {
308
            $this->saveOrder();
309
            $this->updateBdInfo();
310
        } catch (\Exception $e) {
311
            $exceptionObject = new \stdClass();
312
            $exceptionObject->method= __FUNCTION__;
313
            $exceptionObject->status='500';
314
            $exceptionObject->result= self::PMO_ERR_MSG;
315
            $exceptionObject->result_description = $e->getMessage();
316
            throw new \Exception(serialize($exceptionObject));
317
        }
318
    }
319
320
    private function confirmPmtOrder()
321
    {
322
        try {
323
            $this->pmtOrder = $this->orderClient->confirmOrder($this->pmtOrderId);
324
        } catch (\Exception $e) {
325
            $exceptionObject = new \stdClass();
326
            $exceptionObject->method= __FUNCTION__;
327
            $exceptionObject->status='500';
328
            $exceptionObject->result= self::CPO_ERR_MSG;
329
            $exceptionObject->result_description = $e->getMessage();
330
            throw new \Exception(serialize($exceptionObject));
331
        }
332
333
        $response = array();
334
        $response['status'] = '200';
335
        $response['timestamp'] = time();
336
        $response['order_id']= $this->magentoOrderId;
337
        $response['result'] = self::CPO_OK_MSG;
338
        $response = json_encode($response);
339
        return $response;
340
    }
341
342
    /**
343
     * UTILS FUNCTIONS
344
     */
345
346
    /** STEP 1 CC - Check concurrency */
347
    /**
348
     * @throws \Exception
349
     */
350
    private function getQuoteId()
351
    {
352
        $this->quoteId = $this->getRequest()->getParam('quoteId');
353
        if ($this->quoteId == '') {
354
            throw new \Exception(self::CC_NO_QUOTE);
355
        }
356
    }
357
358
    /**
359
     * @return \Zend_Db_Statement_Interface
360
     */
361
    private function checkDbTable()
362
    {
363
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
364
        $dbConnection = $this->dbObject->getConnection();
365
        $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
366
        $query = "CREATE TABLE IF NOT EXISTS $tableName(`id` int not null,`timestamp` int not null,PRIMARY KEY (`id`))";
367
        return $dbConnection->query($query);
368
    }
369
370
    /**
371
     * @return void|\Zend_Db_Statement_Interface
372
     * @throws \Zend_Db_Exception
373
     */
374
    private function checkDbLogTable()
375
    {
376
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
377
        $dbConnection = $this->dbObject->getConnection();
378
        $tableName = $this->dbObject->getTableName(self::LOGS_TABLE);
379
        if (!$dbConnection->isTableExists($tableName)) {
380
            $table = $dbConnection
381
                ->newTable($tableName)
382
                ->addColumn('id', Table::TYPE_SMALLINT, null, array('nullable'=>false, 'auto_increment'=>true, 'primary'=>true))
383
                ->addColumn('log', Table::TYPE_TEXT, null, array('nullable'=>false))
384
                ->addColumn('createdAt', Table::TYPE_TIMESTAMP, null, array('nullable'=>false, 'default'=>Table::TIMESTAMP_INIT));
385
            return $dbConnection->createTable($table);
386
        }
387
388
        return;
389
    }
390
391
    /**
392
     * @param bool $mode
393
     *
394
     * @throws \Exception
395
     */
396
    private function unblockConcurrency($mode = false)
397
    {
398
        try {
399
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
400
            $dbConnection = $this->dbObject->getConnection();
401
            $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
402
            if ($mode == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
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...
403
                $dbConnection->delete($tableName, "timestamp<".(time() - 5));
404
            } elseif ($this->quoteId!='') {
405
                $dbConnection->delete($tableName, "id=".$this->quoteId);
406
            }
407
        } catch (Exception $exception) {
0 ignored issues
show
Bug introduced by
The type DigitalOrigin\Pmt\Controller\Notify\Exception was not found. Did you mean Exception? If so, make sure to prefix the type with \.
Loading history...
408
            throw new \Exception($exception->getMessage());
409
        }
410
    }
411
412
    /**
413
     * @throws \Exception
414
     */
415
    private function blockConcurrency()
416
    {
417
        try {
418
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
419
            $dbConnection = $this->dbObject->getConnection();
420
            $tableName    = $this->dbObject->getTableName(self::CONCURRENCY_TABLE);
421
            $dbConnection->insert($tableName, array('id'=>$this->quoteId, 'timestamp'=>time()));
422
        } catch (Exception $exception) {
423
            throw new \Exception(self::CC_NO_VALIDATE);
424
        }
425
    }
426
427
    /** STEP 2 GMO - Get Merchant Order */
428
    /** STEP 3 GPOI - Get Pmt OrderId */
429
    /**
430
     * @throws \Exception
431
     */
432
    private function getPmtOrderIdDb()
433
    {
434
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
435
        $dbConnection = $this->dbObject->getConnection();
436
        $tableName    = $this->dbObject->getTableName(self::ORDERS_TABLE);
437
        $query        = "select order_id from $tableName where id='$this->quoteId'";
438
        $queryResult  = $dbConnection->fetchRow($query);
439
        $this->pmtOrderId = $queryResult['order_id'];
440
        if ($this->pmtOrderId == '') {
441
            throw new \Exception(self::GPOI_NO_ORDERID);
442
        }
443
    }
444
445
    /** STEP 4 GPO - Get Pmt Order */
446
    /** STEP 5 COS - Check Order Status */
447
    /**
448
     * @param $statusArray
449
     *
450
     * @throws \Exception
451
     */
452
    private function checkPmtStatus($statusArray)
453
    {
454
        $pmtStatus = array();
455
        foreach ($statusArray as $status) {
456
            $pmtStatus[] = constant("\PagaMasTarde\OrdersApiClient\Model\Order::STATUS_$status");
457
        }
458
459
        $payed = in_array($this->pmtOrder->getStatus(), $pmtStatus);
460
        if (!$payed) {
461
            throw new \Exception(self::CMOS_ERR_MSG."=>".$this->pmtOrder->getStatus());
462
        }
463
    }
464
465
    /** STEP 6 CMOS - Check Merchant Order Status */
466
    /**
467
     * @throws \Exception
468
     */
469
    private function checkCartStatus()
470
    {
471
        if ($this->quote->getIsActive()=='0') {
472
            $this->getMagentoOrderId();
473
            throw new \Exception(self::CMOS_ALREADY_PROCESSED);
474
        }
475
    }
476
477
    private function getMagentoOrderId()
478
    {
479
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
480
        $dbConnection = $this->dbObject->getConnection();
481
        $tableName    = $this->dbObject->getTableName(self::ORDERS_TABLE);
482
        $pmtOrderId   = $this->pmtOrderId;
483
484
        $query        = "select mg_order_id from $tableName where id='$this->quoteId' and order_id='$pmtOrderId'";
485
        $queryResult  = $dbConnection->fetchRow($query);
486
        $this->magentoOrderId = $queryResult['mg_order_id'];
487
    }
488
489
    /** STEP 7 VA - Validate Amount */
490
    /**
491
     * @throws \Exception
492
     */
493
    private function comparePrices()
494
    {
495
        $grandTotal = $this->quote->getGrandTotal();
496
        if ($this->pmtOrder->getShoppingCart()->getTotalAmount() != intval(strval(100 * $grandTotal))) {
497
            throw new \Exception(self::VA_ERR_MSG);
498
        }
499
    }
500
501
    /** STEP 8 PMO - Process Merchant Order */
502
    /**
503
     * @throws \Magento\Framework\Exception\CouldNotSaveException
504
     */
505
    private function saveOrder()
506
    {
507
        $this->paymentInterface->setMethod(self::PAYMENT_METHOD);
508
        $this->magentoOrderId = $this->quoteManagement->placeOrder($this->quoteId, $this->paymentInterface);
509
        /** @var \Magento\Sales\Api\Data\OrderInterface magentoOrder */
510
        $this->magentoOrder = $this->orderRepositoryInterface->get($this->magentoOrderId);
511
512
        if ($this->magentoOrderId == '') {
513
            throw new \Exception(self::PMO_ERR_MSG);
514
        }
515
    }
516
517
    private function updateBdInfo()
518
    {
519
        /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
520
        $dbConnection = $this->dbObject->getConnection();
521
        $tableName    = $this->dbObject->getTableName(self::ORDERS_TABLE);
522
        $pmtOrderId   = $this->pmtOrder->getId();
523
        $dbConnection->update(
524
            $tableName,
525
            array('mg_order_id'=>$this->magentoOrderId),
526
            "order_id='$pmtOrderId' and id='$this->quoteId'"
527
        );
528
    }
529
530
    /** STEP 9 CPO - Confirmation Pmt Order */
531
    private function rollbackMerchantOrder()
532
    {
533
        $this->magentoOrder->setState(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT, true);
0 ignored issues
show
Unused Code introduced by
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

533
        $this->magentoOrder->/** @scrutinizer ignore-call */ 
534
                             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...
534
        $this->magentoOrder->setStatus(\Magento\Sales\Model\Order::STATE_PENDING_PAYMENT);
535
        $this->magentoOrder->save();
536
    }
537
538
    /**
539
     * @return string
540
     */
541
    private function getRedirectUrl()
542
    {
543
        $returnUrl = 'checkout/#payment';
544
        if ($this->magentoOrderId!='') {
545
            /** @var Order $this->magentoOrder */
546
            $this->magentoOrder = $this->orderRepositoryInterface->get($this->magentoOrderId);
547
            if (!$this->_objectManager->get(\Magento\Checkout\Model\Session\SuccessValidator::class)->isValid()) {
548
                $this->checkoutSession
549
                    ->setLastOrderId($this->magentoOrderId)
550
                    ->setLastRealOrderId($this->magentoOrder->getIncrementId())
551
                    ->setLastQuoteId($this->quoteId)
552
                    ->setLastSuccessQuoteId($this->quoteId)
553
                    ->setLastOrderStatus($this->magentoOrder->getStatus());
554
            }
555
556
            //Magento status flow => https://docs.magento.com/m2/ce/user_guide/sales/order-status-workflow.html
557
            //Order Workflow => https://docs.magento.com/m2/ce/user_guide/sales/order-workflow.html
558
            $orderStatus    = strtolower($this->magentoOrder->getStatus());
559
            $acceptedStatus = array('processing', 'completed');
560
            if (in_array($orderStatus, $acceptedStatus)) {
561
                if ($this->config['ok_url'] != '') {
562
                    $returnUrl = $this->config['ok_url'];
563
                } else {
564
                    $returnUrl = 'checkout/onepage/success';
565
                }
566
            } else {
567
                if ($this->config['ko_url'] != '') {
568
                    $returnUrl = $this->config['ko_url'];
569
                } else {
570
                    $returnUrl = 'checkout/#payment';
571
                }
572
            }
573
        }
574
        return $returnUrl;
575
    }
576
577
    /**
578
     * @param $exceptionMessage
579
     *
580
     * @throws \Zend_Db_Exception
581
     */
582
    private function insertLog($exceptionMessage)
583
    {
584
        if ($exceptionMessage instanceof \Exception) {
585
            $this->checkDbLogTable();
586
            $logObject          = new \stdClass();
587
            $logObject->message = $exceptionMessage->getMessage();
588
            $logObject->code    = $exceptionMessage->getCode();
589
            $logObject->line    = $exceptionMessage->getLine();
590
            $logObject->file    = $exceptionMessage->getFile();
591
            $logObject->trace   = $exceptionMessage->getTraceAsString();
592
593
            /** @var \Magento\Framework\DB\Adapter\AdapterInterface $dbConnection */
594
            $dbConnection = $this->dbObject->getConnection();
595
            $tableName    = $this->dbObject->getTableName(self::LOGS_TABLE);
596
            $dbConnection->insert($tableName, array('log' => json_encode($logObject)));
597
        }
598
    }
599
}
600