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

notifyController::processInformation()   A

Complexity

Conditions 3
Paths 15

Size

Total Lines 26
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 22
nc 15
nop 0
dl 0
loc 26
rs 9.568
c 1
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
    /**
49
     * Validation vs PagantisClient
50
     *
51
     * @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...
52
     * @throws Exception
53
     */
54
    public function processInformation()
55
    {
56
        require_once('vendor/autoload.php');
57
        try {
58
            $this->checkConcurrency();
59
            $this->getMerchantOrder();
60
            $this->getPagantisOrderId();
61
            $this->getPagantisOrder();
62
            $this->checkOrderStatus();
63
            $this->checkMerchantOrderStatus();
64
            $this->validateAmount();
65
            //$this->processMerchantOrder(); //ESTE PASO SE HACE EN EL CHECKOUT_PROCESS
66
        } catch (\Exception $exception) {
67
            $jsonResponse = new JsonExceptionResponse();
68
            $jsonResponse->setMerchantOrderId($this->oscommerceOrderId);
69
            $jsonResponse->setPagantisOrderId($this->pagantisOrderId);
70
            $jsonResponse->setException($exception);
71
            $response = $jsonResponse->toJson();
0 ignored issues
show
Unused Code introduced by
The assignment to $response is dead and can be removed.
Loading history...
72
            $this->insertLog($exception);
73
            $shippingUrl = trim(tep_href_link(FILENAME_CHECKOUT_SHIPPING, '', 'SSL', false));
0 ignored issues
show
Bug introduced by
The constant FILENAME_CHECKOUT_SHIPPING was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
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

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

142
        $resultsSelect = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
143
        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

143
        while ($orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect)) {
Loading history...
144
            $this->pagantisOrderId = $orderRow['pagantis_order_id'];
145
        }
146
147
        if ($this->pagantisOrderId == '') {
148
            throw new NoIdentificationException();
149
        }
150
    }
151
152
    /**
153
     * @throws OrderNotFoundException
154
     */
155
    private function getPagantisOrder()
156
    {
157
        try {
158
            $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...
159
            $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...
160
            $this->orderClient   = new \Pagantis\OrdersApiClient\Client($publicKey, $secretKey);
161
            $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId);
162
        } catch (\Exception $e) {
163
            throw new OrderNotFoundException();
164
        }
165
    }
166
167
    /**
168
     * @throws AlreadyProcessedException
169
     * @throws WrongStatusException
170
     */
171
    private function checkOrderStatus()
172
    {
173
        try {
174
            $this->checkPagantisStatus(array('AUTHORIZED'));
175
        } catch (\Exception $e) {
176
            if ($this->findOscommerceOrderId()!=='') {
177
                return;
178
            } else {
179
                if ($this->pagantisOrder instanceof \Pagantis\OrdersApiClient\Model\Order) {
180
                    $status = $this->pagantisOrder->getStatus();
181
                } else {
182
                    $status = '-';
183
                }
184
                throw new WrongStatusException($status);
185
            }
186
        }
187
    }
188
189
    /**
190
     * @throws AlreadyProcessedException
191
     */
192
    private function checkMerchantOrderStatus()
193
    {
194
        global $order;
195
196
        if ($order->info['order_status']!=='1') {
197
            throw new AlreadyProcessedException();
198
        }
199
    }
200
201
    /**
202
     * @throws AmountMismatchException
203
     */
204
    private function validateAmount()
205
    {
206
        $pagantisAmount = $this->pagantisOrder->getShoppingCart()->getTotalAmount();
207
        $ocAmount = intval($this->oscommerceOrder->info['total'] * 100);
208
209
        if ($pagantisAmount != $ocAmount) {
210
            throw new AmountMismatchException($pagantisAmount, $ocAmount);
211
        }
212
    }
213
214
    /**
215
     * @return false|string
216
     * @throws UnknownException
217
     */
218
    private function confirmPagantisOrder()
219
    {
220
        try {
221
            $this->pagantisOrder = $this->orderClient->confirmOrder($this->pagantisOrderId);
222
        } catch (\Exception $e) {
223
            throw new UnknownException($e->getMessage());
224
        }
225
226
        $jsonResponse = new JsonSuccessResponse();
227
        return $jsonResponse->toJson();
228
    }
229
    /**
230
     * UTILS FUNCTIONS
231
     */
232
233
    /** STEP 1 CC - Check concurrency */
234
235
    /**
236
     * @throws QuoteNotFoundException
237
     */
238
    private function getQuoteId()
239
    {
240
        if ($this->oscommerceOrderId == "") {
241
            throw new QuoteNotFoundException();
242
        }
243
    }
244
245
    /**
246
     * Check if concurrency table exists
247
     */
248
    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...
249
    {
250
        $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

250
        $checkTable = /** @scrutinizer ignore-call */ tep_db_query("SHOW TABLES LIKE '".TABLE_PAGANTIS_CONCURRENCY."'");
Loading history...
251
        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

251
        if (/** @scrutinizer ignore-call */ tep_db_num_rows($checkTable) == 0) {
Loading history...
252
            $sql = "CREATE TABLE IF NOT EXISTS ".TABLE_PAGANTIS_CONCURRENCY." (
253
                            id int NOT NULL,
254
                            `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
255
                            UNIQUE KEY id(id))";
256
            tep_db_query($sql);
257
        }
258
        return;
259
    }
260
261
    /**
262
     * Unlock the concurrency
263
     *
264
     * @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...
265
     * @throws Exception
266
     */
267
    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...
268
    {
269
        try {
270
            if ($orderId == null) {
0 ignored issues
show
introduced by
The condition $orderId == null is always true.
Loading history...
271
                $query = "delete from ".TABLE_PAGANTIS_CONCURRENCY." where  timestamp<".(time() - 5);
272
                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

272
                /** @scrutinizer ignore-call */ 
273
                tep_db_query($query);
Loading history...
273
            } elseif ($this->$orderId!='') {
274
                $query = "delete from ".TABLE_PAGANTIS_CONCURRENCY." where id='$orderId'";
275
                tep_db_query($query);
276
            }
277
        } catch (Exception $exception) {
278
            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...
279
        }
280
    }
281
282
    /**
283
     * @throws \Exception
284
     */
285
    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...
286
    {
287
        try {
288
            $query = "INSERT INTO ".TABLE_PAGANTIS_CONCURRENCY." (id) VALUES ('$this->oscommerceOrderId')";
289
            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

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

332
        $resultsSelect = /** @scrutinizer ignore-call */ tep_db_query($query);
Loading history...
333
        $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

333
        $orderRow = /** @scrutinizer ignore-call */ tep_db_fetch_array($resultsSelect);
Loading history...
334
335
        return $orderRow['os_order_id'];
336
    }
337
338
    /** STEP 6 CMOS - Check Merchant Order Status */
339
    /** STEP 7 VA - Validate Amount */
340
    /** STEP 8 PMO - Process Merchant Order */
341
342
    /**
343
     * Save the order status with the related identification
344
     */
345
    private function updateBdInfo()
346
    {
347
        global $insert_id, $order;
348
        $query = "update ".TABLE_PAGANTIS_ORDERS." set os_order_id='$insert_id' where os_order_reference='$this->oscommerceOrderId'";
349
        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

349
        /** @scrutinizer ignore-call */ 
350
        tep_db_query($query);
Loading history...
350
351
        $comment = "Pagantis id=$this->pagantisOrderId/Via=".$this->origin;
352
        $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...
353
            ('$comment', ".$insert_id.", '2', -1, now() )";
354
        tep_db_query($query);
355
356
        $query = "update ".TABLE_ORDERS." set orders_status='2' where orders_id='$insert_id'";
0 ignored issues
show
Bug introduced by
The constant TABLE_ORDERS was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
357
        tep_db_query($query);
358
    }
359
360
    /** STEP 9 CPO - Confirmation Pagantis Order */
361
    private function rollbackMerchantOrder()
362
    {
363
        global $insert_id;
364
        $query = "update orders set order_status='1' where orders_id='$insert_id' ";
365
        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

365
        /** @scrutinizer ignore-call */ 
366
        tep_db_query($query);
Loading history...
366
    }
367
368
    /**
369
     * @param $exception
370
     */
371
    private function insertLog($exception)
372
    {
373
        if ($exception instanceof \Exception) {
374
            $logEntry= new LogEntry();
375
            $logEntryJson = $logEntry->error($exception)->toJson();
376
377
            $query = "insert into ".TABLE_PAGANTIS_LOG."(log) values ('$logEntryJson')";
378
            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

378
            /** @scrutinizer ignore-call */ 
379
            tep_db_query($query);
Loading history...
379
        }
380
    }
381
382
    /***
383
     * SETTERS Y GETTERS
384
     */
385
386
    /**
387
     * @return mixed
388
     */
389
    public function getOscommerceOrderId()
390
    {
391
        return $this->oscommerceOrderId;
392
    }
393
394
    /**
395
     * @param $oscommerceOrderId
396
     */
397
    public function setOscommerceOrderId($oscommerceOrderId)
398
    {
399
        $this->oscommerceOrderId = $oscommerceOrderId;
400
    }
401
402
    /**
403
     * @return mixed
404
     */
405
    public function getOrigin()
406
    {
407
        return $this->origin;
408
    }
409
410
    /**
411
     * @param mixed $origin
412
     */
413
    public function setOrigin($origin)
414
    {
415
        $this->origin = $origin;
416
    }
417
418
    /**
419
     * @return String
420
     */
421
    public function getOrderStatus()
422
    {
423
        return $this->orderStatus;
424
    }
425
426
    /**
427
     * @param String $orderStatus
428
     */
429
    public function setOrderStatus($orderStatus)
430
    {
431
        $this->orderStatus = $orderStatus;
0 ignored issues
show
Bug Best Practice introduced by
The property orderStatus does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
432
    }
433
}
434