Total Complexity | 67 |
Total Lines | 556 |
Duplicated Lines | 0 % |
Changes | 1 | ||
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 | /** Concurrency tablename */ |
||
25 | const CONCURRENCY_TABLE = 'pagantis_concurrency'; |
||
26 | |||
27 | /** Seconds to expire a locked request */ |
||
28 | const CONCURRENCY_TIMEOUT = 5; |
||
29 | |||
30 | /** @var mixed $pagantisOrder */ |
||
31 | protected $pagantisOrder; |
||
32 | |||
33 | /** @var $string $origin */ |
||
|
|||
34 | public $origin; |
||
35 | |||
36 | /** @var $string */ |
||
37 | public $order; |
||
38 | |||
39 | /** @var mixed $woocommerceOrderId */ |
||
40 | protected $woocommerceOrderId = ''; |
||
41 | |||
42 | /** @var mixed $cfg */ |
||
43 | protected $cfg; |
||
44 | |||
45 | /** @var Client $orderClient */ |
||
46 | protected $orderClient; |
||
47 | |||
48 | /** @var WC_Order $woocommerceOrder */ |
||
49 | protected $woocommerceOrder; |
||
50 | |||
51 | /** @var mixed $pagantisOrderId */ |
||
52 | protected $pagantisOrderId = ''; |
||
53 | |||
54 | /** @var $string */ |
||
55 | protected $product; |
||
56 | |||
57 | /** @var $string */ |
||
58 | protected $token; |
||
59 | |||
60 | /** |
||
61 | * Validation vs PagantisClient |
||
62 | * |
||
63 | * @return JsonExceptionResponse|JsonSuccessResponse |
||
64 | * @throws ConcurrencyException |
||
65 | */ |
||
66 | public function processInformation() |
||
67 | { |
||
68 | try { |
||
69 | require_once(__ROOT__.'/vendor/autoload.php'); |
||
70 | try { |
||
71 | if ($_SERVER['REQUEST_METHOD'] == 'GET' && $_GET['origin'] == 'notification') { |
||
72 | return $this->buildResponse(); |
||
73 | } |
||
74 | $this->checkConcurrency(); |
||
75 | $this->getProductType(); |
||
76 | $this->getMerchantOrder(); |
||
77 | $this->getPagantisOrderId(); |
||
78 | $this->getPagantisOrder(); |
||
79 | $checkAlreadyProcessed = $this->checkOrderStatus(); |
||
80 | if ($checkAlreadyProcessed) { |
||
81 | return $this->buildResponse(); |
||
82 | } |
||
83 | $this->validateAmount(); |
||
84 | if ($this->checkMerchantOrderStatus()) { |
||
85 | $this->processMerchantOrder(); |
||
86 | } |
||
87 | } catch (\Exception $exception) { |
||
88 | $this->insertLog($exception); |
||
89 | |||
90 | return $this->buildResponse($exception); |
||
91 | } |
||
92 | |||
93 | try { |
||
94 | $this->confirmPagantisOrder(); |
||
95 | |||
96 | return $this->buildResponse(); |
||
97 | } catch (\Exception $exception) { |
||
98 | $this->rollbackMerchantOrder(); |
||
99 | $this->insertLog($exception); |
||
100 | |||
101 | return $this->buildResponse($exception); |
||
102 | } |
||
103 | } catch (\Exception $exception) { |
||
104 | $this->insertLog($exception); |
||
105 | return $this->buildResponse($exception); |
||
106 | } |
||
107 | } |
||
108 | |||
109 | /** |
||
110 | * COMMON FUNCTIONS |
||
111 | */ |
||
112 | |||
113 | /** |
||
114 | * @throws ConcurrencyException |
||
115 | * @throws QuoteNotFoundException |
||
116 | */ |
||
117 | private function checkConcurrency() |
||
118 | { |
||
119 | $this->woocommerceOrderId = $_GET['order-received']; |
||
120 | if ($this->woocommerceOrderId == '') { |
||
121 | throw new QuoteNotFoundException(); |
||
122 | } |
||
123 | |||
124 | $this->unblockConcurrency(); |
||
125 | $this->blockConcurrency($this->woocommerceOrderId); |
||
126 | } |
||
127 | |||
128 | /** |
||
129 | * getProductType |
||
130 | */ |
||
131 | private function getProductType() |
||
132 | { |
||
133 | if ($_GET['product'] == '') { |
||
134 | $this->setProduct(WcPagantisGateway::METHOD_ID); |
||
135 | } else { |
||
136 | $this->setProduct($_GET['product']); |
||
137 | } |
||
138 | } |
||
139 | |||
140 | /** |
||
141 | * @throws MerchantOrderNotFoundException |
||
142 | */ |
||
143 | private function getMerchantOrder() |
||
144 | { |
||
145 | try { |
||
146 | $this->woocommerceOrder = new WC_Order($this->woocommerceOrderId); |
||
147 | $this->woocommerceOrder->set_payment_method_title($this->getProduct()); |
||
148 | } catch (\Exception $e) { |
||
149 | throw new MerchantOrderNotFoundException(); |
||
150 | } |
||
151 | } |
||
152 | |||
153 | /** |
||
154 | * @throws NoIdentificationException |
||
155 | */ |
||
156 | private function getPagantisOrderId() |
||
166 | } |
||
167 | } |
||
168 | |||
169 | /** |
||
170 | * @throws OrderNotFoundException |
||
171 | */ |
||
172 | private function getPagantisOrder() |
||
189 | } |
||
190 | } |
||
191 | |||
192 | /** |
||
193 | * @return bool |
||
194 | * @throws WrongStatusException |
||
195 | */ |
||
196 | private function checkOrderStatus() |
||
211 | } |
||
212 | } |
||
213 | |||
214 | /** |
||
215 | * @return bool |
||
216 | */ |
||
217 | private function checkMerchantOrderStatus() |
||
218 | { |
||
219 | //Order status reference => https://docs.woocommerce.com/document/managing-orders/ |
||
220 | $validStatus = array('on-hold', 'pending', 'failed', 'processing', 'completed'); |
||
221 | $isValidStatus = apply_filters( |
||
222 | 'woocommerce_valid_order_statuses_for_payment_complete', |
||
223 | $validStatus, |
||
224 | $this |
||
225 | ); |
||
226 | |||
227 | if (!$this->woocommerceOrder->has_status($isValidStatus)) { // TO CONFIRM |
||
228 | $logMessage = "WARNING checkMerchantOrderStatus." . |
||
229 | " Merchant order id:".$this->woocommerceOrder->get_id(). |
||
230 | " Merchant order status:".$this->woocommerceOrder->get_status(). |
||
231 | " Pagantis order id:".$this->pagantisOrder->getStatus(). |
||
232 | " Pagantis order status:".$this->pagantisOrder->getId(). |
||
233 | " Pagantis urlToken: ".$this->token; |
||
234 | |||
235 | $this->insertLog(null, $logMessage); |
||
236 | $this->woocommerceOrder->add_order_note($logMessage); |
||
237 | $this->woocommerceOrder->save(); |
||
238 | return false; |
||
239 | } |
||
240 | |||
241 | return true; //TO SAVE |
||
242 | } |
||
243 | |||
244 | /** |
||
245 | * @throws AmountMismatchException |
||
246 | */ |
||
247 | private function validateAmount() |
||
248 | { |
||
249 | $pagantisAmount = $this->pagantisOrder->getShoppingCart()->getTotalAmount(); |
||
250 | $wcAmount = intval(strval(100 * $this->woocommerceOrder->get_total())); |
||
251 | if ($pagantisAmount != $wcAmount) { |
||
252 | throw new AmountMismatchException($pagantisAmount, $wcAmount); |
||
253 | } |
||
254 | } |
||
255 | |||
256 | /** |
||
257 | * @throws Exception |
||
258 | */ |
||
259 | private function processMerchantOrder() |
||
260 | { |
||
261 | $this->saveOrder(); |
||
262 | $this->updateBdInfo(); |
||
263 | } |
||
264 | |||
265 | /** |
||
266 | * @return false|string |
||
267 | * @throws UnknownException |
||
268 | */ |
||
269 | private function confirmPagantisOrder() |
||
270 | { |
||
271 | try { |
||
272 | $this->pagantisOrder = $this->orderClient->confirmOrder($this->pagantisOrderId); |
||
273 | } catch (\Exception $e) { |
||
274 | $this->pagantisOrder = $this->orderClient->getOrder($this->pagantisOrderId); |
||
275 | if ($this->pagantisOrder->getStatus() !== Order::STATUS_CONFIRMED) { |
||
276 | throw new UnknownException($e->getMessage()); |
||
277 | } else { |
||
278 | $logMessage = 'Concurrency issue: Order_id '.$this->pagantisOrderId.' was confirmed by other process'; |
||
279 | $this->insertLog(null, $logMessage); |
||
280 | } |
||
281 | } |
||
282 | |||
283 | $jsonResponse = new JsonSuccessResponse(); |
||
284 | return $jsonResponse->toJson(); |
||
285 | } |
||
286 | |||
287 | /** |
||
288 | * UTILS FUNCTIONS |
||
289 | */ |
||
290 | /** STEP 1 CC - Check concurrency */ |
||
291 | |||
292 | /** |
||
293 | * Check if cart processing table exists |
||
294 | */ |
||
295 | private function checkDbTable() |
||
296 | { |
||
297 | if (isPgTableCreated(PG_CART_PROCESS_TABLE)){ |
||
298 | alterCartProcessingTable(); |
||
299 | } else{ |
||
300 | createCartProcessingTable(); |
||
301 | } |
||
302 | } |
||
303 | |||
304 | /** |
||
305 | * Check if logs table exists |
||
306 | */ |
||
307 | private function checkDbLogTable() |
||
308 | { |
||
309 | global $wpdb; |
||
310 | $tableName = $wpdb->prefix.PG_LOGS_TABLE_NAME; |
||
311 | |||
312 | if ($wpdb->get_var("SHOW TABLES LIKE '$tableName'") != $tableName) { |
||
313 | $charset_collate = $wpdb->get_charset_collate(); |
||
314 | $sql = "CREATE TABLE $tableName ( id int NOT NULL AUTO_INCREMENT, log text NOT NULL, |
||
315 | createdAt timestamp DEFAULT CURRENT_TIMESTAMP, UNIQUE KEY id (id)) $charset_collate"; |
||
316 | |||
317 | require_once(ABSPATH.'wp-admin/includes/upgrade.php'); |
||
318 | dbDelta($sql); |
||
319 | } |
||
320 | return; |
||
321 | } |
||
322 | |||
323 | /** STEP 2 GMO - Get Merchant Order */ |
||
324 | /** STEP 3 GPOI - Get Pagantis OrderId */ |
||
325 | /** STEP 4 GPO - Get Pagantis Order */ |
||
326 | /** STEP 5 COS - Check Order Status */ |
||
327 | |||
328 | /** |
||
329 | * @param $statusArray |
||
330 | * |
||
331 | * @throws \Exception |
||
332 | */ |
||
333 | private function checkPagantisStatus($statusArray) |
||
352 | } |
||
353 | } |
||
354 | |||
355 | /** STEP 6 CMOS - Check Merchant Order Status */ |
||
356 | /** STEP 7 VA - Validate Amount */ |
||
357 | /** STEP 8 PMO - Process Merchant Order */ |
||
358 | /** |
||
359 | * @throws \Exception |
||
360 | */ |
||
361 | private function saveOrder() |
||
362 | { |
||
363 | global $woocommerce; |
||
364 | $paymentResult = $this->woocommerceOrder->payment_complete(); |
||
365 | if ($paymentResult) { |
||
366 | $metadataOrder = $this->pagantisOrder->getMetadata(); |
||
367 | $metadataInfo = null; |
||
368 | foreach ($metadataOrder as $metadataKey => $metadataValue) { |
||
369 | if ($metadataKey == 'promotedProduct') { |
||
370 | $metadataInfo.= "/Producto promocionado = $metadataValue"; |
||
371 | } |
||
372 | } |
||
373 | |||
374 | if ($metadataInfo != null) { |
||
375 | $this->woocommerceOrder->add_order_note($metadataInfo); |
||
376 | } |
||
377 | |||
378 | $this->woocommerceOrder->add_order_note("Notification received via $this->origin"); |
||
379 | $this->woocommerceOrder->reduce_order_stock(); |
||
380 | $this->woocommerceOrder->save(); |
||
381 | |||
382 | $woocommerce->cart->empty_cart(); |
||
383 | sleep(3); |
||
384 | } else { |
||
385 | throw new UnknownException('Order can not be saved'); |
||
386 | } |
||
387 | } |
||
388 | |||
389 | /** |
||
390 | * Save the merchant order_id with the related identification |
||
391 | */ |
||
392 | private function updateBdInfo() |
||
393 | { |
||
394 | global $wpdb; |
||
395 | |||
396 | $this->checkDbTable(); |
||
397 | $tableName = $wpdb->prefix.PG_CART_PROCESS_TABLE; |
||
398 | |||
399 | $wpdb->update( |
||
400 | $tableName, |
||
401 | array('wc_order_id'=>$this->woocommerceOrderId), |
||
402 | array('token' => $this->token), |
||
403 | array('%s,%s'), |
||
404 | array('%s,%s') |
||
405 | ); |
||
406 | } |
||
407 | |||
408 | /** STEP 9 CPO - Confirmation Pagantis Order */ |
||
409 | private function rollbackMerchantOrder() |
||
410 | { |
||
411 | $this->woocommerceOrder->update_status('pending', __('Pending payment', 'woocommerce')); |
||
412 | } |
||
413 | |||
414 | /** |
||
415 | * @param null $exception |
||
416 | * @param null $message |
||
417 | */ |
||
418 | private function insertLog($exception = null, $message = null) |
||
419 | { |
||
420 | global $wpdb; |
||
421 | |||
422 | $this->checkDbLogTable(); |
||
423 | $logEntry = new LogEntry(); |
||
424 | if ($exception instanceof \Exception) { |
||
425 | $logEntry = $logEntry->error($exception); |
||
426 | } else { |
||
427 | $logEntry = $logEntry->info($message); |
||
428 | } |
||
429 | |||
430 | $tableName = $wpdb->prefix.PG_LOGS_TABLE_NAME; |
||
431 | $wpdb->insert($tableName, array('log' => $logEntry->toJson())); |
||
432 | } |
||
433 | |||
434 | /** |
||
435 | * @param null $orderId |
||
436 | * |
||
437 | * @throws ConcurrencyException |
||
438 | */ |
||
439 | private function unblockConcurrency($orderId = null) |
||
440 | { |
||
441 | global $wpdb; |
||
442 | $tableName = $wpdb->prefix.PG_CONCURRENCY_TABLE_NAME; |
||
443 | if ($orderId == null) { |
||
444 | $query = "DELETE FROM $tableName WHERE createdAt<(NOW()- INTERVAL ".self::CONCURRENCY_TIMEOUT." SECOND)"; |
||
445 | } else { |
||
446 | $query = "DELETE FROM $tableName WHERE order_id = $orderId"; |
||
447 | } |
||
448 | $resultDelete = $wpdb->query($query); |
||
449 | if ($resultDelete === false) { |
||
450 | throw new ConcurrencyException(); |
||
451 | } |
||
452 | } |
||
453 | |||
454 | /** |
||
455 | * @param $orderId |
||
456 | * |
||
457 | * @throws ConcurrencyException |
||
458 | */ |
||
459 | private function blockConcurrency($orderId) |
||
460 | { |
||
461 | global $wpdb; |
||
462 | $tableName = $wpdb->prefix.PG_CONCURRENCY_TABLE_NAME; |
||
463 | $insertResult = $wpdb->insert($tableName, array('order_id' => $orderId)); |
||
464 | if ($insertResult === false) { |
||
465 | if ($this->getOrigin() == 'Notify') { |
||
466 | throw new ConcurrencyException(); |
||
467 | } else { |
||
468 | $query = sprintf( |
||
469 | "SELECT TIMESTAMPDIFF(SECOND,NOW()-INTERVAL %s SECOND, createdAt) as rest FROM %s WHERE %s", |
||
470 | self::CONCURRENCY_TIMEOUT, |
||
471 | $tableName, |
||
472 | "order_id=$orderId" |
||
473 | ); |
||
474 | $resultSeconds = $wpdb->get_row($query); |
||
475 | $restSeconds = isset($resultSeconds) ? ($resultSeconds->rest) : 0; |
||
476 | $secondsToExpire = ($restSeconds>self::CONCURRENCY_TIMEOUT) ? self::CONCURRENCY_TIMEOUT : $restSeconds; |
||
477 | sleep($secondsToExpire+1); |
||
478 | |||
479 | $logMessage = sprintf( |
||
480 | "User waiting %s seconds, default seconds %s, bd time to expire %s seconds", |
||
481 | $secondsToExpire, |
||
482 | self::CONCURRENCY_TIMEOUT, |
||
483 | $restSeconds |
||
484 | ); |
||
485 | $this->insertLog(null, $logMessage); |
||
486 | } |
||
487 | } |
||
488 | } |
||
489 | |||
490 | /** |
||
491 | * @param null $exception |
||
492 | * |
||
493 | * |
||
494 | * @return JsonExceptionResponse|JsonSuccessResponse |
||
495 | * @throws ConcurrencyException |
||
496 | */ |
||
497 | private function buildResponse($exception = null) |
||
498 | { |
||
499 | $this->unblockConcurrency($this->woocommerceOrderId); |
||
500 | $this->setToken($_GET['token']); |
||
501 | pagantisLogger::log( " token " . $_GET['token'] . "on " . __LINE__ . " in " . __FILE__); |
||
502 | pagantisLogger::log( " token " . $this->token . "on " . __LINE__ . " in " . __FILE__); |
||
503 | |||
504 | if ($exception == null) { |
||
505 | $jsonResponse = new JsonSuccessResponse(); |
||
506 | } else { |
||
507 | $jsonResponse = new JsonExceptionResponse(); |
||
508 | $jsonResponse->setException($exception); |
||
509 | } |
||
510 | $jsonResponse->setMerchantOrderId($this->woocommerceOrderId); |
||
511 | $jsonResponse->setPagantisOrderId($this->pagantisOrderId); |
||
512 | |||
513 | if ($_SERVER['REQUEST_METHOD'] == 'POST') { |
||
514 | $jsonResponse->printResponse(); |
||
515 | } else { |
||
516 | return $jsonResponse; |
||
517 | } |
||
518 | } |
||
519 | |||
520 | /** |
||
521 | * GETTERS & SETTERS |
||
522 | */ |
||
523 | |||
524 | /** |
||
525 | * @return mixed |
||
526 | */ |
||
527 | public function getOrigin() |
||
528 | { |
||
529 | return $this->origin; |
||
530 | } |
||
531 | |||
532 | /** |
||
533 | * @param mixed $origin |
||
534 | */ |
||
535 | public function setOrigin($origin) |
||
536 | { |
||
537 | $this->origin = $origin; |
||
538 | } |
||
539 | |||
540 | /** |
||
541 | * @return bool |
||
542 | */ |
||
543 | private function isProduct4x() |
||
546 | } |
||
547 | |||
548 | /** |
||
549 | * @return mixed |
||
550 | */ |
||
551 | public function getProduct() |
||
552 | { |
||
553 | return $this->product; |
||
554 | } |
||
555 | |||
556 | /** |
||
557 | * @param mixed $product |
||
558 | */ |
||
559 | public function setProduct($product) |
||
562 | } |
||
563 | |||
564 | /** |
||
565 | * @param $token |
||
566 | */ |
||
567 | public function setToken($token) |
||
570 | } |
||
571 | |||
572 | /** |
||
573 | * @return mixed |
||
574 | */ |
||
575 | public function getToken() |
||
578 | } |
||
579 | |||
580 | } |
||
581 |