| 1 |
<?php namespace TierPricingTable\Addons\GlobalTieredPricing; |
| 2 |
|
| 3 |
use TierPricingTable\Addons\GlobalTieredPricing\CPT\GlobalTieredPricingCPT; |
| 4 |
use TierPricingTable\PriceManager; |
| 5 |
|
| 6 |
class GlobalTieredPricingCartManager { |
| 7 |
|
| 8 |
/** |
| 9 |
* Pricing rules |
| 10 |
* |
| 11 |
* @var GlobalPricingRule[] |
| 12 |
*/ |
| 13 |
public $globalPricingRules = array(); |
| 14 |
|
| 15 |
public function __construct() { |
| 16 |
|
| 17 |
add_action( 'init', function () { |
| 18 |
$this->globalPricingRules = GlobalTieredPricingCPT::getGlobalRules(); |
| 19 |
} ); |
| 20 |
|
| 21 |
add_filter( 'tiered_pricing_table/cart/total_product_count', array( |
| 22 |
$this, |
| 23 |
'calculateCommonQuantities', |
| 24 |
), 10, 2 ); |
| 25 |
} |
| 26 |
|
| 27 |
public function calculateCommonQuantities( $quantity, $cartItem ) { |
| 28 |
|
| 29 |
$globalPricingData = $this->getGlobalPricingDataFromCartItem( $cartItem ); |
| 30 |
|
| 31 |
if ( empty( $globalPricingData ) ) { |
| 32 |
return $quantity; |
| 33 |
} |
| 34 |
|
| 35 |
// Global pricing rule is set to calculate tiered pricing individually |
| 36 |
if ( 'cross' !== $globalPricingData['applying_type'] ) { |
| 37 |
return $quantity; |
| 38 |
} |
| 39 |
|
| 40 |
// Reset quantity to calculate it from scratch |
| 41 |
$quantity = 0; |
| 42 |
|
| 43 |
foreach ( wc()->cart->get_cart_contents() as $_cartItem ) { |
| 44 |
|
| 45 |
$_globalPricingData = $this->getGlobalPricingDataFromCartItem( $_cartItem ); |
| 46 |
|
| 47 |
// This is a different pricing rule |
| 48 |
if ( empty( $_globalPricingData['id'] ) || $_globalPricingData['id'] !== $globalPricingData['id'] ) { |
| 49 |
continue; |
| 50 |
} |
| 51 |
|
| 52 |
// Item has the same global pricing rule as the pricing provider and its set to "mix and match" strategy |
| 53 |
$quantity += $_cartItem['quantity']; |
| 54 |
} |
| 55 |
|
| 56 |
return $quantity; |
| 57 |
} |
| 58 |
|
| 59 |
protected function getGlobalPricingDataFromCartItem( array $cartItem ): array { |
| 60 |
$data = array(); |
| 61 |
|
| 62 |
if ( ! ( $cartItem['data'] instanceof \WC_Product ) ) { |
| 63 |
return $data; |
| 64 |
} |
| 65 |
|
| 66 |
$pricingRule = PriceManager::getPricingRule( $cartItem['data']->get_id() ); |
| 67 |
|
| 68 |
if ( 'global-rules' !== $pricingRule->provider ) { |
| 69 |
return $data; |
| 70 |
} |
| 71 |
|
| 72 |
$data['id'] = $pricingRule->providerData['rule_id'] ?? null; |
| 73 |
$data['applying_type'] = $pricingRule->providerData['applying_type'] ?? null; |
| 74 |
|
| 75 |
return $data; |
| 76 |
} |
| 77 |
} |
| 78 |
|