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