Passed
Pull Request — master (#4)
by
unknown
02:54
created

notifyController::blockConcurrency()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
nc 2
nop 0
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
use Pagantis\OrdersApiClient\Client;
4
use Pagantis\ModuleUtils\Exception\AlreadyProcessedException;
5
use Pagantis\ModuleUtils\Exception\AmountMismatchException;
6
use Pagantis\ModuleUtils\Exception\MerchantOrderNotFoundException;
7
use Pagantis\ModuleUtils\Exception\NoIdentificationException;
8
use Pagantis\ModuleUtils\Exception\OrderNotFoundException;
9
use Pagantis\ModuleUtils\Exception\QuoteNotFoundException;
10
use Pagantis\ModuleUtils\Exception\UnknownException;
11
use Pagantis\ModuleUtils\Exception\WrongStatusException;
12
use Pagantis\ModuleUtils\Model\Response\JsonSuccessResponse;
13
use Pagantis\ModuleUtils\Model\Response\JsonExceptionResponse;
14
use Pagantis\ModuleUtils\Model\Log\LogEntry;
15
16
17
define('TABLE_PAGANTIS_LOG', 'pagantis_log');
18
define('TABLE_PAGANTIS_CONFIG', 'pagantis_config');
19
define('TABLE_PAGANTIS_ORDERS', 'pagantis_orders');
20
define('TABLE_PAGANTIS_CONCURRENCY', 'pagantis_concurrency');
21
22
class notifyController
23
{
24
    /** @var mixed $pagantisOrder */
25
    protected $pagantisOrder;
26
27
    /** @var $string $origin */
0 ignored issues
show
Documentation Bug introduced by
The doc comment $string at position 0 could not be parsed: Unknown type name '$string' at position 0 in $string.
Loading history...
28
    public $origin;
29
30
    /** @var $string */
0 ignored issues
show
Documentation Bug introduced by
The doc comment $string at position 0 could not be parsed: Unknown type name '$string' at position 0 in $string.
Loading history...
31
    public $order;
32
33
    /** @var mixed $oscommerceOrderId */
34
    protected $oscommerceOrderId = '';
35
36
    /** @var mixed $cfg */
37
    protected $cfg;
38
39
    /** @var Client $orderClient */
40
    protected $orderClient;
41
42
    /** @var Order $oscommerceOrder */
0 ignored issues
show
Bug introduced by
The type Order 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...
43
    protected $oscommerceOrder;
44
45
    /** @var mixed $pagantisOrderId */
46
    protected $pagantisOrderId = '';
47
48
    /** @var String $order_status */
49
    protected $orderStatus;
50
51
    /**
52
     * Validation vs PagantisClient
53
     *
54
     * @return array|Array_
0 ignored issues
show
Bug introduced by
The type 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...
55
     * @throws Exception
56
     */
57
    public function processInformation()
58
    {
59
        require_once('vendor/autoload.php');
60
        try {
61
            $this->checkConcurrency();
62
            $this->getMerchantOrder();
63
            $this->getPagantisOrderId();
64
            $this->getPagantisOrder();
65
            $this->checkOrderStatus();
66
            $this->checkMerchantOrderStatus();
67
            $this->validateAmount();
68
            //$this->processMerchantOrder(); //ESTE PASO SE HACE EN EL CHECKOUT_PROCESS
69
        } catch (\Exception $exception) {
70
            $jsonResponse = new JsonExceptionResponse();
71
            $jsonResponse->setMerchantOrderId($this->oscommerceOrderId);
72
            $jsonResponse->setPagantisOrderId($this->pagantisOrderId);
73
            $jsonResponse->setException($exception);
74
            $response = $jsonResponse->toJson();
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
75
            $this->insertLog($exception);
76
            $shippingUrl = trim(tep_href_link(FILENAME_CHECKOUT_SHIPPING, '', 'SSL', false));
0 ignored issues
show
Bug introduced by
The function tep_href_link 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

76
            $shippingUrl = trim(/** @scrutinizer ignore-call */ tep_href_link(FILENAME_CHECKOUT_SHIPPING, '', 'SSL', false));
Loading history...
Bug introduced by
The constant FILENAME_CHECKOUT_SHIPPING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
77
78
            if ($this->origin == 'notify') {
79
                $jsonResponse->printResponse();
80
            } else {
81
                if (get_class($exception)=='AlreadyProcessedException') {
82
                    return;
83
                }
84
85
                header("Location: $shippingUrl");
86
                exit;
87
            }
88
        }
89
    }
90
91
    public function confirmInformation()
92
    {
93
        try {
94
            $this->confirmPagantisOrder();
95
            $this->updateBdInfo();
96
            $jsonResponse = new JsonSuccessResponse();
97
            $jsonResponse->setMerchantOrderId($this->oscommerceOrderId);
98
            $jsonResponse->setPagantisOrderId($this->pagantisOrderId);
99
        } catch (\Exception $exception) {
100
            $this->rollbackMerchantOrder();
101
            $jsonResponse = new JsonExceptionResponse();
102
            $jsonResponse->setMerchantOrderId($this->oscommerceOrderId);
103
            $jsonResponse->setPagantisOrderId($this->pagantisOrderId);
104
            $jsonResponse->setException($exception);
105
            $jsonResponse->toJson();
106
            $this->insertLog($exception);
107
        }
108
109
        if ($_SERVER['REQUEST_METHOD'] == 'POST') {
110
            $jsonResponse->printResponse();
111
        } else {
112
            return $jsonResponse;
113
        }
114
    }
115
116
    /**
117
     * COMMON FUNCTIONS
118
     */
119
120
    /**
121
     * @throws Exception
122
     */
123
    private function checkConcurrency()
124
    {
125
        $this->getQuoteId();
126
        //$this->checkConcurrencyTable();
127
        //$this->unblockConcurrency();
128
        //$this->blockConcurrency();
129
    }
130
131
    /**
132
     * @throws MerchantOrderNotFoundException
133
     */
134
    private function getMerchantOrder()
135
    {
136
        global $order;
137
        $this->oscommerceOrder = $order;
138
        if (!isset($order->info)) {
139
            throw new MerchantOrderNotFoundException();
140
        }
141
    }
142
143
    /**
144
     * @throws NoIdentificationException
145
     */
146
    private function getPagantisOrderId()
147
    {
148
        $query = "select pagantis_order_id from ".TABLE_PAGANTIS_ORDERS." where os_order_reference='".$this->oscommerceOrderId."'";
149
        $resultsSelect = tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query 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

149
        $resultsSelect = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
150
        while ($orderRow = tep_db_fetch_array($resultsSelect)) {
0 ignored issues
show
Bug introduced by
The function tep_db_fetch_array 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

150
        while ($orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect)) {
Loading history...
151
            $this->pagantisOrderId = $orderRow['pagantis_order_id'];
152
        }
153
154
        if ($this->pagantisOrderId == '') {
155
            throw new NoIdentificationException();
156
        }
157
    }
158
159
    /**
160
     * @throws OrderNotFoundException
161
     */
162
    private function getPagantisOrder()
163
    {
164
        try {
165
            $publicKey     = trim(MODULE_PAYMENT_PAGANTIS_PK);
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_PK was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
166
            $secretKey     = trim(MODULE_PAYMENT_PAGANTIS_SK);
0 ignored issues
show
Bug introduced by
The constant MODULE_PAYMENT_PAGANTIS_SK was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
167
            $this->orderClient   = new \Pagantis\OrdersApiClient\Client($publicKey, $secretKey);
168
            $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId);
169
        } catch (\Exception $e) {
170
            throw new OrderNotFoundException();
171
        }
172
    }
173
174
    /**
175
     * @throws AlreadyProcessedException
176
     * @throws WrongStatusException
177
     */
178
    private function checkOrderStatus()
179
    {
180
        try {
181
            $this->checkPagantisStatus(array('AUTHORIZED'));
182
        } catch (\Exception $e) {
183
            if ($this->findOscommerceOrderId()!=='') {
184
                throw new AlreadyProcessedException();
185
            } else {
186
                if ($this->pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
187
                    $status = $this->pagantisOrder->getStatus();
188
                } else {
189
                    $status = '-';
190
                }
191
                throw new WrongStatusException($status);
192
            }
193
        }
194
    }
195
196
    /**
197
     * @throws AlreadyProcessedException
198
     */
199
    private function checkMerchantOrderStatus()
200
    {
201
        global $order;
202
203
        if ($order->info['order_status']!=='1') {
204
            throw new AlreadyProcessedException();
205
        }
206
    }
207
208
    /**
209
     * @throws AmountMismatchException
210
     */
211
    private function validateAmount()
212
    {
213
        $pagantisAmount = $this->pagantisOrder->getShoppingCart()->getTotalAmount();
214
        $ocAmount = intval($this->oscommerceOrder->info['total'] * 100);
215
216
        if ($pagantisAmount != $ocAmount) {
217
            throw new AmountMismatchException($pagantisAmount, $ocAmount);
218
        }
219
    }
220
221
    /**
222
     * @return false|string
223
     * @throws UnknownException
224
     */
225
    private function confirmPagantisOrder()
226
    {
227
        try {
228
            $this->pagantisOrder = $this->orderClient->confirmOrder($this->pagantisOrderId);
229
        } catch (\Exception $e) {
230
            throw new UnknownException($e->getMessage());
231
        }
232
233
        $jsonResponse = new JsonSuccessResponse();
234
        return $jsonResponse->toJson();
235
    }
236
    /**
237
     * UTILS FUNCTIONS
238
     */
239
240
    /** STEP 1 CC - Check concurrency */
241
242
    /**
243
     * @throws QuoteNotFoundException
244
     */
245
    private function getQuoteId()
246
    {
247
        if ($this->oscommerceOrderId == "") {
248
            throw new QuoteNotFoundException();
249
        }
250
    }
251
252
    /**
253
     * Check if concurrency table exists
254
     */
255
    private function checkConcurrencyTable()
0 ignored issues
show
Unused Code introduced by
The method checkConcurrencyTable() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
256
    {
257
        $checkTable = tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONCURRENCY."'");
0 ignored issues
show
Bug introduced by
The function tep_db_query 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

257
        $checkTable = /** @scrutinizer ignore-call */ tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONCURRENCY."'");
Loading history...
258
        if (tep_db_num_rows($checkTable) == 0) {
0 ignored issues
show
Bug introduced by
The function tep_db_num_rows 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

258
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) == 0) {
Loading history...
259
            $sql = "CREATE TABLE IF NOT EXISTS ".TABLE_PAGANTIS_CONCURRENCY." (
260
                            id int NOT NULL,
261
                            `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
262
                            UNIQUE KEY id(id))";
263
            tep_db_query($sql);
264
        }
265
        return;
266
    }
267
268
    /**
269
     * Unlock the concurrency
270
     *
271
     * @param null $orderId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $orderId is correct as it would always require null to be passed?
Loading history...
272
     * @throws Exception
273
     */
274
    private function unblockConcurrency($orderId = null)
0 ignored issues
show
Unused Code introduced by
The method unblockConcurrency() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
275
    {
276
        try {
277
            if ($orderId == null) {
0 ignored issues
show
introduced by
The condition $orderId == null is always true.
Loading history...
278
                $query = "delete from ".TABLE_PAGANTIS_CONCURRENCY." where  timestamp<".(time() - 5);
279
                tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query 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

279
                /** @scrutinizer ignore-call */ 
280
                tep_db_query($query);
Loading history...
280
            } elseif ($this->$orderId!='') {
281
                $query = "delete from ".TABLE_PAGANTIS_CONCURRENCY." where id='$orderId'";
282
                tep_db_query($query);
283
            }
284
        } catch (Exception $exception) {
285
            throw new ConcurrencyException();
0 ignored issues
show
Bug introduced by
The type ConcurrencyException 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...
286
        }
287
    }
288
289
    /**
290
     * @throws \Exception
291
     */
292
    private function blockConcurrency()
0 ignored issues
show
Unused Code introduced by
The method blockConcurrency() is not used, and could be removed.

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
293
    {
294
        try {
295
            $query = "INSERT INTO ".TABLE_PAGANTIS_CONCURRENCY." (id) VALUES ('$this->oscommerceOrderId')";
296
            tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query 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

296
            /** @scrutinizer ignore-call */ 
297
            tep_db_query($query);
Loading history...
297
        } catch (Exception $exception) {
298
            throw new ConcurrencyException();
299
        }
300
    }
301
302
    /** STEP 2 GMO - Get Merchant Order */
303
    /** STEP 3 GPOI - Get Pagantis OrderId */
304
    /** STEP 4 GPO - Get Pagantis Order */
305
    /** STEP 5 COS - Check Order Status */
306
    /**
307
     * @param $statusArray
308
     *
309
     * @throws \Exception
310
     */
311
    private function checkPagantisStatus($statusArray)
312
    {
313
        $pagantisStatus = array();
314
        foreach ($statusArray as $status) {
315
            $pagantisStatus[] = constant("\Pagantis\OrdersApiClient\Model\Order::STATUS_$status");
316
        }
317
318
        if ($this->pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
319
            $payed = in_array($this->pagantisOrder->getStatus(), $pagantisStatus);
320
            if (!$payed) {
321
                if ($this->pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
0 ignored issues
show
introduced by
$this->pagantisOrder is always a sub-type of Pagantis\OrdersApiClient\Model\Order.
Loading history...
322
                    $status = $this->pagantisOrder->getStatus();
323
                } else {
324
                    $status = '-';
325
                }
326
                throw new WrongStatusException($status);
327
            }
328
        } else {
329
            throw new OrderNotFoundException();
330
        }
331
    }
332
333
    /**
334
     * @return mixed
335
     */
336
    private function findOscommerceOrderId()
337
    {
338
        $query = "select os_order_id from ".TABLE_PAGANTIS_ORDERS." where os_order_reference='".$this->oscommerceOrderId."'";
339
        $resultsSelect = tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query 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

339
        $resultsSelect = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
340
        $orderRow = tep_db_fetch_array($resultsSelect);
0 ignored issues
show
Bug introduced by
The function tep_db_fetch_array 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

340
        $orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect);
Loading history...
341
342
        return $orderRow['os_order_id'];
343
    }
344
345
    /** STEP 6 CMOS - Check Merchant Order Status */
346
    /** STEP 7 VA - Validate Amount */
347
    /** STEP 8 PMO - Process Merchant Order */
348
349
    /**
350
     * Save the order status with the related identification
351
     */
352
    private function updateBdInfo()
353
    {
354
        global $insert_id, $order;
355
        $query = "update ".TABLE_PAGANTIS_ORDERS." set os_order_id='$insert_id' where os_order_reference='$this->oscommerceOrderId'";
356
        tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query 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

356
        /** @scrutinizer ignore-call */ 
357
        tep_db_query($query);
Loading history...
357
358
        $comment = "Pagantis id=$this->pagantisOrderId/Via=".$this->origin;
359
        $query = "insert into ".TABLE_ORDERS_STATUS_HISTORY ."(comments, orders_id, orders_status_id, customer_notified, date_added) values
0 ignored issues
show
Bug introduced by
The constant TABLE_ORDERS_STATUS_HISTORY was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
360
            ('$comment', ".$insert_id.", '".$this->orderStatus."', -1, now() )";
361
        tep_db_query($query);
362
    }
363
364
    /** STEP 9 CPO - Confirmation Pagantis Order */
365
    private function rollbackMerchantOrder()
366
    {
367
        global $insert_id;
368
        $query = "update orders set order_status='1' where id='$insert_id' ";
369
        tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query 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

369
        /** @scrutinizer ignore-call */ 
370
        tep_db_query($query);
Loading history...
370
    }
371
372
    /**
373
     * @param $exception
374
     */
375
    private function insertLog($exception)
376
    {
377
        if ($exception instanceof \Exception) {
378
            $logEntry= new LogEntry();
379
            $logEntryJson = $logEntry->error($exception)->toJson();
380
381
            $query = "insert into ".TABLE_PAGANTIS_LOG."(log) values ('$logEntryJson')";
382
            tep_db_query($query);
0 ignored issues
show
Bug introduced by
The function tep_db_query 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

382
            /** @scrutinizer ignore-call */ 
383
            tep_db_query($query);
Loading history...
383
        }
384
    }
385
386
    /***
387
     * SETTERS Y GETTERS
388
     */
389
390
    /**
391
     * @return mixed
392
     */
393
    public function getOscommerceOrderId()
394
    {
395
        return $this->oscommerceOrderId;
396
    }
397
398
    /**
399
     * @param $oscommerceOrderId
400
     */
401
    public function setOscommerceOrderId($oscommerceOrderId)
402
    {
403
        $this->oscommerceOrderId = $oscommerceOrderId;
404
    }
405
406
    /**
407
     * @return mixed
408
     */
409
    public function getOrigin()
410
    {
411
        return $this->origin;
412
    }
413
414
    /**
415
     * @param mixed $origin
416
     */
417
    public function setOrigin($origin)
418
    {
419
        $this->origin = $origin;
420
    }
421
422
    /**
423
     * @return String
424
     */
425
    public function getOrderStatus()
426
    {
427
        return $this->orderStatus;
428
    }
429
430
    /**
431
     * @param String $orderStatus
432
     */
433
    public function setOrderStatus($orderStatus)
434
    {
435
        $this->orderStatus = $orderStatus;
436
    }
437
}
438