Total Complexity | 74 |
Total Lines | 614 |
Duplicated Lines | 0 % |
Changes | 4 | ||
Bugs | 0 | Features | 0 |
Complex classes like WcPagantisNotify often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use WcPagantisNotify, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
22 | class WcPagantisNotify extends WcPagantisGateway |
||
23 | { |
||
24 | |||
25 | |||
26 | /** Seconds to expire a locked request */ |
||
27 | const CONCURRENCY_TIMEOUT = 5; |
||
28 | |||
29 | /** @var mixed $pagantisOrder */ |
||
30 | protected $pagantisOrder; |
||
31 | |||
32 | /** @var $string $origin */ |
||
|
|||
33 | public $origin; |
||
34 | |||
35 | /** @var $string */ |
||
36 | public $order; |
||
37 | |||
38 | /** @var mixed $woocommerceOrderId */ |
||
39 | protected $woocommerceOrderId = ''; |
||
40 | |||
41 | /** @var mixed $cfg */ |
||
42 | protected $cfg; |
||
43 | |||
44 | /** @var Client $orderClient */ |
||
45 | protected $orderClient; |
||
46 | |||
47 | /** @var WC_Order $woocommerceOrder */ |
||
48 | protected $woocommerceOrder; |
||
49 | |||
50 | /** @var mixed $pagantisOrderId */ |
||
51 | protected $pagantisOrderId = ''; |
||
52 | |||
53 | /** @var $string */ |
||
54 | protected $product; |
||
55 | |||
56 | /** @var $string */ |
||
57 | protected $urlToken = null; |
||
58 | |||
59 | /** |
||
60 | * Validation vs PagantisClient |
||
61 | * |
||
62 | * @return JsonExceptionResponse|JsonSuccessResponse |
||
63 | * @throws ConcurrencyException |
||
64 | */ |
||
65 | public function processInformation() |
||
66 | { |
||
67 | try { |
||
68 | require_once(__ROOT__ . '/vendor/autoload.php'); |
||
69 | try { |
||
70 | if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_GET['origin'] == 'notification') { |
||
71 | return $this->buildResponse(); |
||
72 | } |
||
73 | |||
74 | |||
75 | $this->checkConcurrency(); |
||
76 | $this->getProductType(); |
||
77 | $this->getMerchantOrder(); |
||
78 | $this->getPagantisOrderId(); |
||
79 | $this->getPagantisOrder(); |
||
80 | $checkAlreadyProcessed = $this->checkOrderStatus(); |
||
81 | if ($checkAlreadyProcessed) { |
||
82 | return $this->buildResponse(); |
||
83 | } |
||
84 | $this->validateAmount(); |
||
85 | if ($this->checkMerchantOrderStatus()) { |
||
86 | $this->processMerchantOrder(); |
||
87 | } |
||
88 | } catch (\Exception $exception) { |
||
89 | $this->insertLog($exception); |
||
90 | |||
91 | return $this->buildResponse($exception); |
||
92 | } |
||
93 | |||
94 | try { |
||
95 | $this->confirmPagantisOrder(); |
||
96 | |||
97 | return $this->buildResponse(); |
||
98 | } catch (\Exception $exception) { |
||
99 | $this->rollbackMerchantOrder(); |
||
100 | $this->insertLog($exception); |
||
101 | |||
102 | return $this->buildResponse($exception); |
||
103 | } |
||
104 | } catch (\Exception $exception) { |
||
105 | $this->insertLog($exception); |
||
106 | return $this->buildResponse($exception); |
||
107 | } |
||
108 | } |
||
109 | |||
110 | /** |
||
111 | * COMMON FUNCTIONS |
||
112 | */ |
||
113 | |||
114 | /** |
||
115 | * @throws ConcurrencyException|QuoteNotFoundException |
||
116 | */ |
||
117 | private function checkConcurrency() |
||
118 | { |
||
119 | $this->setWoocommerceOrderId(); |
||
120 | $this->unblockConcurrency(); |
||
121 | $this->blockConcurrency($this->woocommerceOrderId); |
||
122 | } |
||
123 | |||
124 | /** |
||
125 | * getProductType |
||
126 | */ |
||
127 | private function getProductType() |
||
128 | { |
||
129 | if ($_GET['product'] == '') { |
||
130 | $this->setProduct(WcPagantisGateway::METHOD_ID); |
||
131 | } else { |
||
132 | $this->setProduct($_GET['product']); |
||
133 | } |
||
134 | } |
||
135 | |||
136 | /** |
||
137 | * @throws MerchantOrderNotFoundException |
||
138 | */ |
||
139 | private function getMerchantOrder() |
||
140 | { |
||
141 | try { |
||
142 | $this->woocommerceOrder = new WC_Order($this->woocommerceOrderId); |
||
143 | $this->woocommerceOrder->set_payment_method_title($this->getProduct()); |
||
144 | } catch (\Exception $e) { |
||
145 | throw new MerchantOrderNotFoundException(); |
||
146 | } |
||
147 | } |
||
148 | |||
149 | /** |
||
150 | * @throws MerchantOrderNotFoundException |
||
151 | */ |
||
152 | private function verifyOrderConformity() |
||
153 | { |
||
154 | global $wpdb; |
||
155 | $this->checkDbTable(); |
||
156 | $tableName =$wpdb->prefix.PG_CART_PROCESS_TABLE; |
||
157 | $tokenCount=$wpdb->get_var($wpdb->prepare( |
||
158 | "SELECT COUNT(order_id) |
||
159 | FROM $tableName |
||
160 | WHERE token=%s", |
||
161 | $this->getUrlToken() |
||
162 | )); |
||
163 | $orderIDCount = $wpdb->get_var( |
||
164 | $wpdb->prepare( |
||
165 | "SELECT COUNT(token) |
||
166 | FROM $tableName |
||
167 | WHERE order_id=%s", |
||
168 | $this->pagantisOrderId |
||
169 | ) |
||
170 | ); |
||
171 | |||
172 | if (!($tokenCount == 1 && $orderIDCount == 1)) { |
||
173 | throw new MerchantOrderNotFoundException(); |
||
174 | } |
||
175 | } |
||
176 | |||
177 | private function getPagantisOrderId() |
||
178 | { |
||
179 | global $wpdb; |
||
180 | $this->setUrlToken(); |
||
181 | $this->checkDbTable(); |
||
182 | $tableName = $wpdb->prefix.PG_CART_PROCESS_TABLE; |
||
183 | $order_id = $wpdb->get_var("SELECT order_id FROM $tableName WHERE token='{$this->getUrlToken()}'"); |
||
184 | $this->pagantisOrderId = $order_id; |
||
185 | |||
186 | if (empty($this->pagantisOrderId)) { |
||
187 | throw new NoIdentificationException(); |
||
188 | } |
||
189 | |||
190 | $this->verifyOrderConformity(); |
||
191 | } |
||
192 | |||
193 | |||
194 | |||
195 | /** |
||
196 | * @throws OrderNotFoundException |
||
197 | */ |
||
198 | private function getPagantisOrder() |
||
199 | { |
||
200 | try { |
||
201 | $this->cfg = get_option('woocommerce_pagantis_settings'); |
||
202 | $this->cfg = get_option('woocommerce_pagantis_settings'); |
||
203 | if ($this->isProduct4x()) { |
||
204 | $publicKey = $this->cfg['pagantis_public_key_4x']; |
||
205 | $secretKey = $this->cfg['pagantis_private_key_4x']; |
||
206 | } else { |
||
207 | $publicKey = $this->cfg['pagantis_public_key']; |
||
208 | $secretKey = $this->cfg['pagantis_private_key']; |
||
209 | } |
||
210 | |||
211 | $this->orderClient = new Client($publicKey, $secretKey); |
||
212 | $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId); |
||
213 | } catch (\Exception $e) { |
||
214 | throw new OrderNotFoundException(); |
||
215 | } |
||
216 | } |
||
217 | |||
218 | /** |
||
219 | * @return bool |
||
220 | * @throws WrongStatusException |
||
221 | */ |
||
222 | private function checkOrderStatus() |
||
223 | { |
||
224 | try { |
||
225 | $this->checkPagantisStatus(array('AUTHORIZED')); |
||
226 | } catch (\Exception $e) { |
||
227 | if ($this->pagantisOrder instanceof Order) { |
||
228 | $status = $this->pagantisOrder->getStatus(); |
||
229 | } else { |
||
230 | $status = '-'; |
||
231 | } |
||
232 | |||
233 | if ($status === Order::STATUS_CONFIRMED) { |
||
234 | return true; |
||
235 | } |
||
236 | throw new WrongStatusException($status); |
||
237 | } |
||
238 | } |
||
239 | |||
240 | /** |
||
241 | * @return bool |
||
242 | */ |
||
243 | private function checkMerchantOrderStatus() |
||
244 | { |
||
245 | //Order status reference => https://docs.woocommerce.com/document/managing-orders/ |
||
246 | $validStatus=array('on-hold', 'pending', 'failed', 'processing', 'completed'); |
||
247 | $isValidStatus = apply_filters( |
||
248 | 'woocommerce_valid_order_statuses_for_payment_complete', |
||
249 | $validStatus, |
||
250 | $this |
||
251 | ); |
||
252 | |||
253 | if (!$this->woocommerceOrder->has_status($isValidStatus)) { // TO CONFIRM |
||
254 | $logMessage = "WARNING checkMerchantOrderStatus." . |
||
255 | " Merchant order id:".$this->woocommerceOrder->get_id(). |
||
256 | " Merchant order status:".$this->woocommerceOrder->get_status(). |
||
257 | " Pagantis order id:".$this->pagantisOrder->getStatus(). |
||
258 | " Pagantis order status:".$this->pagantisOrder->getId(); |
||
259 | $this->insertLog(null, $logMessage); |
||
260 | $this->woocommerceOrder->add_order_note($logMessage); |
||
261 | $this->woocommerceOrder->save(); |
||
262 | return false; |
||
263 | } |
||
264 | |||
265 | return true; //TO SAVE |
||
266 | } |
||
267 | |||
268 | /** |
||
269 | * @throws AmountMismatchException |
||
270 | */ |
||
271 | private function validateAmount() |
||
272 | { |
||
273 | $pagantisAmount = $this->pagantisOrder->getShoppingCart()->getTotalAmount(); |
||
274 | $wcAmount = intval(strval(100 * $this->woocommerceOrder->get_total())); |
||
275 | if ($pagantisAmount != $wcAmount) { |
||
276 | throw new AmountMismatchException($pagantisAmount, $wcAmount); |
||
277 | } |
||
278 | } |
||
279 | |||
280 | /** |
||
281 | * @throws Exception |
||
282 | */ |
||
283 | private function processMerchantOrder() |
||
284 | { |
||
285 | $this->saveOrder(); |
||
286 | $this->updateBdInfo(); |
||
287 | } |
||
288 | |||
289 | /** |
||
290 | * @return false|string |
||
291 | * @throws UnknownException |
||
292 | */ |
||
293 | private function confirmPagantisOrder() |
||
294 | { |
||
295 | try { |
||
296 | $this->pagantisOrder = $this->orderClient->confirmOrder($this->pagantisOrderId); |
||
297 | } catch (\Exception $e) { |
||
298 | $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId); |
||
299 | if ($this->pagantisOrder->getStatus() !== Order::STATUS_CONFIRMED) { |
||
300 | throw new UnknownException($e->getMessage()); |
||
301 | } else { |
||
302 | $logMessage = 'Concurrency issue: Order_id '.$this->pagantisOrderId.' was confirmed by other process'; |
||
303 | $this->insertLog(null, $logMessage); |
||
304 | } |
||
305 | } |
||
306 | |||
307 | $jsonResponse = new JsonSuccessResponse(); |
||
308 | return $jsonResponse->toJson(); |
||
309 | } |
||
310 | |||
311 | /** |
||
312 | * UTILS FUNCTIONS |
||
313 | */ |
||
314 | /** STEP 1 CC - Check concurrency */ |
||
315 | |||
316 | /** |
||
317 | * Check if cart processing table exists |
||
318 | */ |
||
319 | private function checkDbTable() |
||
320 | { |
||
321 | |||
322 | global $wpdb; |
||
323 | $tableName = $wpdb->prefix.PG_CART_PROCESS_TABLE; |
||
324 | if (isPgTableCreated(PG_CART_PROCESS_TABLE)) { |
||
325 | alterCartProcessingTable(); |
||
326 | } |
||
327 | if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) { |
||
328 | $charset_collate = $wpdb->get_charset_collate(); |
||
329 | $sql = "CREATE TABLE IF NOT EXISTS $tableName |
||
330 | (id VARCHAR(60) NOT NULL, |
||
331 | order_id VARCHAR(60) NOT NULL, |
||
332 | wc_order_id VARCHAR(50) NOT NULL, |
||
333 | token VARCHAR(32) NOT NULL, |
||
334 | PRIMARY KEY(id,order_id))$charset_collate"; |
||
335 | |||
336 | require_once(ABSPATH.'wp-admin/includes/upgrade.php'); |
||
337 | dbDelta($sql); |
||
338 | } |
||
339 | } |
||
340 | |||
341 | /** |
||
342 | * Check if logs table exists |
||
343 | */ |
||
344 | private function checkDbLogTable() |
||
345 | { |
||
346 | global $wpdb; |
||
347 | $tableName = $wpdb->prefix.PG_LOGS_TABLE_NAME; |
||
348 | |||
349 | if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) { |
||
350 | $charset_collate = $wpdb->get_charset_collate(); |
||
351 | $sql = "CREATE TABLE $tableName ( id int NOT NULL AUTO_INCREMENT, log text NOT NULL, |
||
352 | createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (id)) $charset_collate"; |
||
353 | |||
354 | require_once(ABSPATH.'wp-admin/includes/upgrade.php'); |
||
355 | dbDelta($sql); |
||
356 | } |
||
357 | return; |
||
358 | } |
||
359 | |||
360 | /** STEP 2 GMO - Get Merchant Order */ |
||
361 | /** STEP 3 GPOI - Get Pagantis OrderId */ |
||
362 | /** STEP 4 GPO - Get Pagantis Order */ |
||
363 | /** STEP 5 COS - Check Order Status */ |
||
364 | |||
365 | /** |
||
366 | * @param $statusArray |
||
367 | * |
||
368 | * @throws \Exception |
||
369 | */ |
||
370 | private function checkPagantisStatus($statusArray) |
||
389 | } |
||
390 | } |
||
391 | |||
392 | /** STEP 6 CMOS - Check Merchant Order Status */ |
||
393 | /** STEP 7 VA - Validate Amount */ |
||
394 | /** STEP 8 PMO - Process Merchant Order */ |
||
395 | /** |
||
396 | * @throws \Exception |
||
397 | */ |
||
398 | private function saveOrder() |
||
399 | { |
||
400 | global $woocommerce; |
||
401 | $paymentResult = $this->woocommerceOrder->payment_complete(); |
||
402 | if ($paymentResult) { |
||
403 | $metadataOrder = $this->pagantisOrder->getMetadata(); |
||
404 | $metadataInfo = null; |
||
405 | foreach ($metadataOrder as $metadataKey => $metadataValue) { |
||
406 | if ($metadataKey == 'promotedProduct') { |
||
407 | $metadataInfo.= "/Producto promocionado = $metadataValue"; |
||
408 | } |
||
409 | } |
||
410 | |||
411 | if ($metadataInfo != null) { |
||
412 | $this->woocommerceOrder->add_order_note($metadataInfo); |
||
413 | } |
||
414 | |||
415 | $this->woocommerceOrder->add_order_note("Notification received via $this->origin"); |
||
416 | $this->woocommerceOrder->reduce_order_stock(); |
||
417 | $this->woocommerceOrder->save(); |
||
418 | |||
419 | $woocommerce->cart->empty_cart(); |
||
420 | sleep(3); |
||
421 | } else { |
||
422 | throw new UnknownException('Order can not be saved'); |
||
423 | } |
||
424 | } |
||
425 | |||
426 | /** |
||
427 | * Save the merchant order_id with the related identification |
||
428 | */ |
||
429 | private function updateBdInfo() |
||
430 | { |
||
431 | global $wpdb; |
||
432 | |||
433 | $this->checkDbTable(); |
||
434 | $tableName = $wpdb->prefix.PG_CART_PROCESS_TABLE; |
||
435 | |||
436 | $wpdb->update( |
||
437 | $tableName, |
||
438 | array('wc_order_id' => $this->woocommerceOrderId,array('order_id' => $this->pagantisOrderId)), |
||
439 | array('token' => $this->getUrlToken()), |
||
440 | array('%s','%s'), |
||
441 | array('%s') |
||
442 | ); |
||
443 | } |
||
444 | |||
445 | /** STEP 9 CPO - Confirmation Pagantis Order */ |
||
446 | private function rollbackMerchantOrder() |
||
447 | { |
||
448 | $this->woocommerceOrder->update_status('pending', __('Pending payment', 'woocommerce')); |
||
449 | } |
||
450 | |||
451 | /** |
||
452 | * @param null $exception |
||
453 | * @param null $message |
||
454 | */ |
||
455 | private function insertLog($exception = null, $message = null) |
||
456 | { |
||
457 | global $wpdb; |
||
458 | |||
459 | $this->checkDbLogTable(); |
||
460 | $logEntry = new LogEntry(); |
||
461 | if ($exception instanceof \Exception) { |
||
462 | $logEntry = $logEntry->error($exception); |
||
463 | } else { |
||
464 | $logEntry = $logEntry->info($message); |
||
465 | } |
||
466 | |||
467 | $tableName = $wpdb->prefix.PG_LOGS_TABLE_NAME; |
||
468 | $wpdb->insert($tableName, array('log' => $logEntry->toJson())); |
||
469 | } |
||
470 | |||
471 | /** |
||
472 | * @param null $orderId |
||
473 | * |
||
474 | * @throws ConcurrencyException |
||
475 | */ |
||
476 | private function unblockConcurrency($orderId = null) |
||
477 | { |
||
478 | global $wpdb; |
||
479 | $tableName = $wpdb->prefix.PG_CONCURRENCY_TABLE_NAME; |
||
480 | if ($orderId == null) { |
||
481 | $query = "DELETE FROM $tableName WHERE createdAt<(NOW()- INTERVAL ".self::CONCURRENCY_TIMEOUT." SECOND)"; |
||
482 | } else { |
||
483 | $query = "DELETE FROM $tableName WHERE order_id = $orderId"; |
||
484 | } |
||
485 | $resultDelete = $wpdb->query($query); |
||
486 | if ($resultDelete === false) { |
||
487 | throw new ConcurrencyException(); |
||
488 | } |
||
489 | } |
||
490 | |||
491 | /** |
||
492 | * @param $orderId |
||
493 | * |
||
494 | * @throws ConcurrencyException |
||
495 | */ |
||
496 | private function blockConcurrency($orderId) |
||
497 | { |
||
498 | global $wpdb; |
||
499 | $tableName = $wpdb->prefix.PG_CONCURRENCY_TABLE_NAME; |
||
500 | $insertResult = $wpdb->insert($tableName, array('order_id' => $orderId)); |
||
501 | if ($insertResult === false) { |
||
502 | if ($this->getOrigin() == 'Notify') { |
||
503 | throw new ConcurrencyException(); |
||
504 | } else { |
||
505 | $query = |
||
506 | sprintf( |
||
507 | "SELECT TIMESTAMPDIFF(SECOND,NOW()-INTERVAL %s SECOND, createdAt) as rest FROM %s WHERE %s", |
||
508 | self::CONCURRENCY_TIMEOUT, |
||
509 | $tableName, |
||
510 | "order_id=$orderId" |
||
511 | ); |
||
512 | $resultSeconds=$wpdb->get_row($query); |
||
513 | $restSeconds =isset($resultSeconds) ? ($resultSeconds->rest) : 0; |
||
514 | $secondsToExpire = ($restSeconds > self::CONCURRENCY_TIMEOUT) ? self::CONCURRENCY_TIMEOUT : $restSeconds; |
||
515 | sleep($secondsToExpire + 1); |
||
516 | |||
517 | $logMessage = |
||
518 | sprintf( |
||
519 | "User waiting %s seconds, default seconds %s, bd time to expire %s seconds", |
||
520 | $secondsToExpire, |
||
521 | self::CONCURRENCY_TIMEOUT, |
||
522 | $restSeconds |
||
523 | ); |
||
524 | $this->insertLog(null, $logMessage); |
||
525 | } |
||
526 | } |
||
527 | } |
||
528 | |||
529 | /** |
||
530 | * @param null $exception |
||
531 | * |
||
532 | * |
||
533 | * @return JsonExceptionResponse|JsonSuccessResponse |
||
534 | * @throws ConcurrencyException |
||
535 | */ |
||
536 | private function buildResponse($exception = null) |
||
537 | { |
||
538 | $this->unblockConcurrency($this->woocommerceOrderId); |
||
539 | |||
540 | if ($exception == null) { |
||
541 | $jsonResponse = new JsonSuccessResponse(); |
||
542 | } else { |
||
543 | $jsonResponse = new JsonExceptionResponse(); |
||
544 | $jsonResponse->setException($exception); |
||
545 | } |
||
546 | $jsonResponse->setMerchantOrderId($this->woocommerceOrderId); |
||
547 | $jsonResponse->setPagantisOrderId($this->pagantisOrderId); |
||
548 | |||
549 | if ($_SERVER['REQUEST_METHOD'] == 'POST') { |
||
550 | $jsonResponse->printResponse(); |
||
551 | } else { |
||
552 | return $jsonResponse; |
||
553 | } |
||
554 | } |
||
555 | |||
556 | /** |
||
557 | * GETTERS & SETTERS |
||
558 | */ |
||
559 | |||
560 | /** |
||
561 | * @return mixed |
||
562 | */ |
||
563 | public function getOrigin() |
||
564 | { |
||
565 | return $this->origin; |
||
566 | } |
||
567 | |||
568 | /** |
||
569 | * @param mixed $origin |
||
570 | */ |
||
571 | public function setOrigin($origin) |
||
572 | { |
||
573 | $this->origin = $origin; |
||
574 | } |
||
575 | |||
576 | /** |
||
577 | * @return bool |
||
578 | */ |
||
579 | private function isProduct4x() |
||
582 | } |
||
583 | |||
584 | /** |
||
585 | * @return mixed |
||
586 | */ |
||
587 | public function getProduct() |
||
588 | { |
||
589 | return $this->product; |
||
590 | } |
||
591 | |||
592 | /** |
||
593 | * @param mixed $product |
||
594 | */ |
||
595 | public function setProduct($product) |
||
598 | } |
||
599 | |||
600 | /** |
||
601 | * @return mixed |
||
602 | */ |
||
603 | public function getWoocommerceOrderId() |
||
604 | { |
||
605 | return $this->woocommerceOrderId; |
||
606 | } |
||
607 | |||
608 | /** |
||
609 | * @throws QuoteNotFoundException |
||
610 | */ |
||
611 | public function setWoocommerceOrderId() |
||
612 | { |
||
613 | $this->woocommerceOrderId = $_GET['order-received']; |
||
614 | if ($this->woocommerceOrderId == '') { |
||
615 | throw new QuoteNotFoundException(); |
||
616 | } |
||
617 | } |
||
618 | |||
619 | /** |
||
620 | * @return mixed |
||
621 | */ |
||
622 | private function getUrlToken() |
||
623 | { |
||
624 | return $this->urlToken; |
||
625 | } |
||
626 | |||
627 | /** |
||
628 | * @throws MerchantOrderNotFoundException |
||
629 | */ |
||
630 | private function setUrlToken() |
||
636 | } |
||
637 | } |
||
638 | } |
||
639 |