Total Complexity | 74 |
Total Lines | 613 |
Duplicated Lines | 0 % |
Changes | 3 | ||
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 |
||
116 | */ |
||
117 | private function checkConcurrency() |
||
118 | { |
||
119 | $this->unblockConcurrency(); |
||
120 | $this->blockConcurrency($this->woocommerceOrderId); |
||
121 | } |
||
122 | |||
123 | /** |
||
124 | * getProductType |
||
125 | */ |
||
126 | private function getProductType() |
||
127 | { |
||
128 | if ($_GET['product'] == '') { |
||
129 | $this->setProduct(WcPagantisGateway::METHOD_ID); |
||
130 | } else { |
||
131 | $this->setProduct($_GET['product']); |
||
132 | } |
||
133 | } |
||
134 | |||
135 | /** |
||
136 | * @throws MerchantOrderNotFoundException |
||
137 | */ |
||
138 | private function getMerchantOrder() |
||
139 | { |
||
140 | try { |
||
141 | $this->woocommerceOrder = new WC_Order($this->woocommerceOrderId); |
||
142 | $this->woocommerceOrder->set_payment_method_title($this->getProduct()); |
||
143 | } catch (\Exception $e) { |
||
144 | throw new MerchantOrderNotFoundException(); |
||
145 | } |
||
146 | } |
||
147 | |||
148 | /** |
||
149 | * @throws MerchantOrderNotFoundException |
||
150 | */ |
||
151 | private function verifyOrderConformity() |
||
152 | { |
||
153 | global $wpdb; |
||
154 | $this->checkDbTable(); |
||
155 | $tableName =$wpdb->prefix.PG_CART_PROCESS_TABLE; |
||
156 | $tokenCount=$wpdb->get_var($wpdb->prepare( |
||
157 | "SELECT COUNT(order_id) |
||
158 | FROM $tableName |
||
159 | WHERE token=%s", |
||
160 | $this->getUrlToken() |
||
161 | )); |
||
162 | $orderIDCount = $wpdb->get_var( |
||
163 | $wpdb->prepare( |
||
164 | "SELECT COUNT(token) |
||
165 | FROM $tableName |
||
166 | WHERE order_id=%s", |
||
167 | $this->pagantisOrderId |
||
168 | ) |
||
169 | ); |
||
170 | |||
171 | if (!($tokenCount == 1 && $orderIDCount == 1)) { |
||
172 | throw new MerchantOrderNotFoundException(); |
||
173 | } |
||
174 | } |
||
175 | |||
176 | private function getPagantisOrderId() |
||
177 | { |
||
178 | global $wpdb; |
||
179 | $this->checkDbTable(); |
||
180 | $tableName = $wpdb->prefix.PG_CART_PROCESS_TABLE; |
||
181 | $queryResult = $wpdb->get_row("SELECT order_id FROM $tableName WHERE token='{$this->getUrlToken()}'"); |
||
182 | $this->pagantisOrderId = $queryResult->order_id; |
||
183 | |||
184 | if (empty($this->pagantisOrderId)) { |
||
185 | throw new NoIdentificationException(); |
||
186 | } |
||
187 | $this->setWoocommerceOrderId(); |
||
188 | $this->setUrlToken(); |
||
189 | $this->verifyOrderConformity(); |
||
190 | } |
||
191 | |||
192 | |||
193 | |||
194 | /** |
||
195 | * @throws OrderNotFoundException |
||
196 | */ |
||
197 | private function getPagantisOrder() |
||
214 | } |
||
215 | } |
||
216 | |||
217 | /** |
||
218 | * @return bool |
||
219 | * @throws WrongStatusException |
||
220 | */ |
||
221 | private function checkOrderStatus() |
||
236 | } |
||
237 | } |
||
238 | |||
239 | /** |
||
240 | * @return bool |
||
241 | */ |
||
242 | private function checkMerchantOrderStatus() |
||
243 | { |
||
244 | //Order status reference => https://docs.woocommerce.com/document/managing-orders/ |
||
245 | $validStatus=array('on-hold', 'pending', 'failed', 'processing', 'completed'); |
||
246 | $isValidStatus = apply_filters( |
||
247 | 'woocommerce_valid_order_statuses_for_payment_complete', |
||
248 | $validStatus, |
||
249 | $this |
||
250 | ); |
||
251 | |||
252 | if (!$this->woocommerceOrder->has_status($isValidStatus)) { // TO CONFIRM |
||
253 | $logMessage = "WARNING checkMerchantOrderStatus." . |
||
254 | " Merchant order id:".$this->woocommerceOrder->get_id(). |
||
255 | " Merchant order status:".$this->woocommerceOrder->get_status(). |
||
256 | " Pagantis order id:".$this->pagantisOrder->getStatus(). |
||
257 | " Pagantis order status:".$this->pagantisOrder->getId(); |
||
258 | $this->insertLog(null, $logMessage); |
||
259 | $this->woocommerceOrder->add_order_note($logMessage); |
||
260 | $this->woocommerceOrder->save(); |
||
261 | return false; |
||
262 | } |
||
263 | |||
264 | return true; //TO SAVE |
||
265 | } |
||
266 | |||
267 | /** |
||
268 | * @throws AmountMismatchException |
||
269 | */ |
||
270 | private function validateAmount() |
||
271 | { |
||
272 | $pagantisAmount = $this->pagantisOrder->getShoppingCart()->getTotalAmount(); |
||
273 | $wcAmount = intval(strval(100 * $this->woocommerceOrder->get_total())); |
||
274 | if ($pagantisAmount != $wcAmount) { |
||
275 | throw new AmountMismatchException($pagantisAmount, $wcAmount); |
||
276 | } |
||
277 | } |
||
278 | |||
279 | /** |
||
280 | * @throws Exception |
||
281 | */ |
||
282 | private function processMerchantOrder() |
||
283 | { |
||
284 | $this->saveOrder(); |
||
285 | $this->updateBdInfo(); |
||
286 | } |
||
287 | |||
288 | /** |
||
289 | * @return false|string |
||
290 | * @throws UnknownException |
||
291 | */ |
||
292 | private function confirmPagantisOrder() |
||
293 | { |
||
294 | try { |
||
295 | $this->pagantisOrder = $this->orderClient->confirmOrder($this->pagantisOrderId); |
||
296 | } catch (\Exception $e) { |
||
297 | $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId); |
||
298 | if ($this->pagantisOrder->getStatus() !== Order::STATUS_CONFIRMED) { |
||
299 | throw new UnknownException($e->getMessage()); |
||
300 | } else { |
||
301 | $logMessage = 'Concurrency issue: Order_id '.$this->pagantisOrderId.' was confirmed by other process'; |
||
302 | $this->insertLog(null, $logMessage); |
||
303 | } |
||
304 | } |
||
305 | |||
306 | $jsonResponse = new JsonSuccessResponse(); |
||
307 | return $jsonResponse->toJson(); |
||
308 | } |
||
309 | |||
310 | /** |
||
311 | * UTILS FUNCTIONS |
||
312 | */ |
||
313 | /** STEP 1 CC - Check concurrency */ |
||
314 | |||
315 | /** |
||
316 | * Check if cart processing table exists |
||
317 | */ |
||
318 | private function checkDbTable() |
||
319 | { |
||
320 | |||
321 | global $wpdb; |
||
322 | $tableName = $wpdb->prefix.PG_CART_PROCESS_TABLE; |
||
323 | if (isPgTableCreated(PG_CART_PROCESS_TABLE)) { |
||
324 | alterCartProcessingTable(); |
||
325 | } |
||
326 | if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) { |
||
327 | $charset_collate = $wpdb->get_charset_collate(); |
||
328 | $sql = "CREATE TABLE IF NOT EXISTS $tableName |
||
329 | (id VARCHAR(60) NOT NULL, |
||
330 | order_id VARCHAR(60) NOT NULL, |
||
331 | wc_order_id VARCHAR(50) NOT NULL, |
||
332 | token VARCHAR(32) NOT NULL, |
||
333 | PRIMARY KEY(id,order_id))$charset_collate"; |
||
334 | |||
335 | require_once(ABSPATH.'wp-admin/includes/upgrade.php'); |
||
336 | dbDelta($sql); |
||
337 | } |
||
338 | } |
||
339 | |||
340 | /** |
||
341 | * Check if logs table exists |
||
342 | */ |
||
343 | private function checkDbLogTable() |
||
344 | { |
||
345 | global $wpdb; |
||
346 | $tableName = $wpdb->prefix.PG_LOGS_TABLE_NAME; |
||
347 | |||
348 | if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) { |
||
349 | $charset_collate = $wpdb->get_charset_collate(); |
||
350 | $sql = "CREATE TABLE $tableName ( id int NOT NULL AUTO_INCREMENT, log text NOT NULL, |
||
351 | createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (id)) $charset_collate"; |
||
352 | |||
353 | require_once(ABSPATH.'wp-admin/includes/upgrade.php'); |
||
354 | dbDelta($sql); |
||
355 | } |
||
356 | return; |
||
357 | } |
||
358 | |||
359 | /** STEP 2 GMO - Get Merchant Order */ |
||
360 | /** STEP 3 GPOI - Get Pagantis OrderId */ |
||
361 | /** STEP 4 GPO - Get Pagantis Order */ |
||
362 | /** STEP 5 COS - Check Order Status */ |
||
363 | |||
364 | /** |
||
365 | * @param $statusArray |
||
366 | * |
||
367 | * @throws \Exception |
||
368 | */ |
||
369 | private function checkPagantisStatus($statusArray) |
||
388 | } |
||
389 | } |
||
390 | |||
391 | /** STEP 6 CMOS - Check Merchant Order Status */ |
||
392 | /** STEP 7 VA - Validate Amount */ |
||
393 | /** STEP 8 PMO - Process Merchant Order */ |
||
394 | /** |
||
395 | * @throws \Exception |
||
396 | */ |
||
397 | private function saveOrder() |
||
398 | { |
||
399 | global $woocommerce; |
||
400 | $paymentResult = $this->woocommerceOrder->payment_complete(); |
||
401 | if ($paymentResult) { |
||
402 | $metadataOrder = $this->pagantisOrder->getMetadata(); |
||
403 | $metadataInfo = null; |
||
404 | foreach ($metadataOrder as $metadataKey => $metadataValue) { |
||
405 | if ($metadataKey == 'promotedProduct') { |
||
406 | $metadataInfo.= "/Producto promocionado = $metadataValue"; |
||
407 | } |
||
408 | } |
||
409 | |||
410 | if ($metadataInfo != null) { |
||
411 | $this->woocommerceOrder->add_order_note($metadataInfo); |
||
412 | } |
||
413 | |||
414 | $this->woocommerceOrder->add_order_note("Notification received via $this->origin"); |
||
415 | $this->woocommerceOrder->reduce_order_stock(); |
||
416 | $this->woocommerceOrder->save(); |
||
417 | |||
418 | $woocommerce->cart->empty_cart(); |
||
419 | sleep(3); |
||
420 | } else { |
||
421 | throw new UnknownException('Order can not be saved'); |
||
422 | } |
||
423 | } |
||
424 | |||
425 | /** |
||
426 | * Save the merchant order_id with the related identification |
||
427 | */ |
||
428 | private function updateBdInfo() |
||
429 | { |
||
430 | global $wpdb; |
||
431 | |||
432 | $this->checkDbTable(); |
||
433 | $tableName = $wpdb->prefix.PG_CART_PROCESS_TABLE; |
||
434 | |||
435 | $wpdb->update( |
||
436 | $tableName, |
||
437 | array('wc_order_id' => $this->woocommerceOrderId,array('order_id' => $this->pagantisOrderId)), |
||
438 | array('token' => $this->getUrlToken()), |
||
439 | array('%s','%s'), |
||
440 | array('%s') |
||
441 | ); |
||
442 | } |
||
443 | |||
444 | /** STEP 9 CPO - Confirmation Pagantis Order */ |
||
445 | private function rollbackMerchantOrder() |
||
446 | { |
||
447 | $this->woocommerceOrder->update_status('pending', __('Pending payment', 'woocommerce')); |
||
448 | } |
||
449 | |||
450 | /** |
||
451 | * @param null $exception |
||
452 | * @param null $message |
||
453 | */ |
||
454 | private function insertLog($exception = null, $message = null) |
||
455 | { |
||
456 | global $wpdb; |
||
457 | |||
458 | $this->checkDbLogTable(); |
||
459 | $logEntry = new LogEntry(); |
||
460 | if ($exception instanceof \Exception) { |
||
461 | $logEntry = $logEntry->error($exception); |
||
462 | } else { |
||
463 | $logEntry = $logEntry->info($message); |
||
464 | } |
||
465 | |||
466 | $tableName = $wpdb->prefix.PG_LOGS_TABLE_NAME; |
||
467 | $wpdb->insert($tableName, array('log' => $logEntry->toJson())); |
||
468 | } |
||
469 | |||
470 | /** |
||
471 | * @param null $orderId |
||
472 | * |
||
473 | * @throws ConcurrencyException |
||
474 | */ |
||
475 | private function unblockConcurrency($orderId = null) |
||
476 | { |
||
477 | global $wpdb; |
||
478 | $tableName = $wpdb->prefix.PG_CONCURRENCY_TABLE_NAME; |
||
479 | if ($orderId == null) { |
||
480 | $query = "DELETE FROM $tableName WHERE createdAt<(NOW()- INTERVAL ".self::CONCURRENCY_TIMEOUT." SECOND)"; |
||
481 | } else { |
||
482 | $query = "DELETE FROM $tableName WHERE order_id = $orderId"; |
||
483 | } |
||
484 | $resultDelete = $wpdb->query($query); |
||
485 | if ($resultDelete === false) { |
||
486 | throw new ConcurrencyException(); |
||
487 | } |
||
488 | } |
||
489 | |||
490 | /** |
||
491 | * @param $orderId |
||
492 | * |
||
493 | * @throws ConcurrencyException |
||
494 | */ |
||
495 | private function blockConcurrency($orderId) |
||
496 | { |
||
497 | global $wpdb; |
||
498 | $tableName = $wpdb->prefix.PG_CONCURRENCY_TABLE_NAME; |
||
499 | $insertResult = $wpdb->insert($tableName, array('order_id' => $orderId)); |
||
500 | if ($insertResult === false) { |
||
501 | if ($this->getOrigin() == 'Notify') { |
||
502 | throw new ConcurrencyException(); |
||
503 | } else { |
||
504 | $query = |
||
505 | sprintf( |
||
506 | "SELECT TIMESTAMPDIFF(SECOND,NOW()-INTERVAL %s SECOND, createdAt) as rest FROM %s WHERE %s", |
||
507 | self::CONCURRENCY_TIMEOUT, |
||
508 | $tableName, |
||
509 | "order_id=$orderId" |
||
510 | ); |
||
511 | $resultSeconds=$wpdb->get_row($query); |
||
512 | $restSeconds =isset($resultSeconds) ? ($resultSeconds->rest) : 0; |
||
513 | $secondsToExpire = ($restSeconds > self::CONCURRENCY_TIMEOUT) ? self::CONCURRENCY_TIMEOUT : $restSeconds; |
||
514 | sleep($secondsToExpire + 1); |
||
515 | |||
516 | $logMessage = |
||
517 | sprintf( |
||
518 | "User waiting %s seconds, default seconds %s, bd time to expire %s seconds", |
||
519 | $secondsToExpire, |
||
520 | self::CONCURRENCY_TIMEOUT, |
||
521 | $restSeconds |
||
522 | ); |
||
523 | $this->insertLog(null, $logMessage); |
||
524 | } |
||
525 | } |
||
526 | } |
||
527 | |||
528 | /** |
||
529 | * @param null $exception |
||
530 | * |
||
531 | * |
||
532 | * @return JsonExceptionResponse|JsonSuccessResponse |
||
533 | * @throws ConcurrencyException |
||
534 | */ |
||
535 | private function buildResponse($exception = null) |
||
536 | { |
||
537 | $this->unblockConcurrency($this->woocommerceOrderId); |
||
538 | |||
539 | if ($exception == null) { |
||
540 | $jsonResponse = new JsonSuccessResponse(); |
||
541 | } else { |
||
542 | $jsonResponse = new JsonExceptionResponse(); |
||
543 | $jsonResponse->setException($exception); |
||
544 | } |
||
545 | $jsonResponse->setMerchantOrderId($this->woocommerceOrderId); |
||
546 | $jsonResponse->setPagantisOrderId($this->pagantisOrderId); |
||
547 | |||
548 | if ($_SERVER['REQUEST_METHOD'] == 'POST') { |
||
549 | $jsonResponse->printResponse(); |
||
550 | } else { |
||
551 | return $jsonResponse; |
||
552 | } |
||
553 | } |
||
554 | |||
555 | /** |
||
556 | * GETTERS & SETTERS |
||
557 | */ |
||
558 | |||
559 | /** |
||
560 | * @return mixed |
||
561 | */ |
||
562 | public function getOrigin() |
||
563 | { |
||
564 | return $this->origin; |
||
565 | } |
||
566 | |||
567 | /** |
||
568 | * @param mixed $origin |
||
569 | */ |
||
570 | public function setOrigin($origin) |
||
571 | { |
||
572 | $this->origin = $origin; |
||
573 | } |
||
574 | |||
575 | /** |
||
576 | * @return bool |
||
577 | */ |
||
578 | private function isProduct4x() |
||
581 | } |
||
582 | |||
583 | /** |
||
584 | * @return mixed |
||
585 | */ |
||
586 | public function getProduct() |
||
587 | { |
||
588 | return $this->product; |
||
589 | } |
||
590 | |||
591 | /** |
||
592 | * @param mixed $product |
||
593 | */ |
||
594 | public function setProduct($product) |
||
597 | } |
||
598 | |||
599 | /** |
||
600 | * @return mixed |
||
601 | */ |
||
602 | public function getWoocommerceOrderId() |
||
603 | { |
||
604 | return $this->woocommerceOrderId; |
||
605 | } |
||
606 | |||
607 | /** |
||
608 | * @throws QuoteNotFoundException |
||
609 | */ |
||
610 | public function setWoocommerceOrderId() |
||
611 | { |
||
612 | $this->woocommerceOrderId = $_GET['order-received']; |
||
613 | if ($this->woocommerceOrderId == '') { |
||
614 | throw new QuoteNotFoundException(); |
||
615 | } |
||
616 | } |
||
617 | |||
618 | /** |
||
619 | * @return mixed |
||
620 | */ |
||
621 | private function getUrlToken() |
||
622 | { |
||
623 | return $this->urlToken; |
||
624 | } |
||
625 | |||
626 | /** |
||
627 | * @throws MerchantOrderNotFoundException |
||
628 | */ |
||
629 | private function setUrlToken() |
||
635 | } |
||
636 | } |
||
637 | } |
||
638 |