| 1 |
<?php namespace TierPricingTable\Addons\GlobalTieredPricing; |
| 2 |
|
| 3 |
use TierPricingTable\Addons\GlobalTieredPricing\CPT\GlobalTieredPricingCPT; |
| 4 |
use TierPricingTable\TierPricingTablePlugin; |
| 5 |
use WC_Product; |
| 6 |
use WP_User; |
| 7 |
|
| 8 |
class GlobalPricingRulesRepository { |
| 9 |
|
| 10 |
protected static $instance; |
| 11 |
|
| 12 |
/** |
| 13 |
* Pricing rules |
| 14 |
* |
| 15 |
* @var GlobalPricingRule[] |
| 16 |
*/ |
| 17 |
protected $rules = array(); |
| 18 |
|
| 19 |
protected $matchedPricingRules = array(); |
| 20 |
|
| 21 |
public static function getInstance(): self { |
| 22 |
if ( ! self::$instance ) { |
| 23 |
self::$instance = new self(); |
| 24 |
} |
| 25 |
|
| 26 |
return self::$instance; |
| 27 |
} |
| 28 |
|
| 29 |
public function getPricingRules(): array { |
| 30 |
if ( empty( $this->rules ) ) { |
| 31 |
$this->rules = GlobalTieredPricingCPT::getGlobalRules(); |
| 32 |
} |
| 33 |
|
| 34 |
return $this->rules; |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Get matched pricing rule for product and user |
| 39 |
* |
| 40 |
* @param WC_Product $product |
| 41 |
* @param ?WP_User $user |
| 42 |
* |
| 43 |
* @return ?GlobalPricingRule |
| 44 |
*/ |
| 45 |
public function getMatchedPricingRule( WC_Product $product, ?WP_User $user = null ): ?GlobalPricingRule { |
| 46 |
|
| 47 |
$user = $user ? $user : TierPricingTablePlugin::getCurrentUser(); |
| 48 |
|
| 49 |
// Cache |
| 50 |
if ( ! isset( $this->matchedPricingRules[ $user->ID ][ $product->get_id() ] ) ) { |
| 51 |
|
| 52 |
$matchedRule = null; |
| 53 |
|
| 54 |
foreach ( $this->getPricingRules() as $globalPricingRule ) { |
| 55 |
if ( $globalPricingRule->matchRequirements( $user, $product ) ) { |
| 56 |
$matchedRule = $globalPricingRule; |
| 57 |
break; |
| 58 |
} |
| 59 |
} |
| 60 |
|
| 61 |
$this->matchedPricingRules[ $user->ID ][ $product->get_id() ] = apply_filters( 'tiered_pricing_table/global_pricing/matched_pricing_rule', |
| 62 |
$matchedRule, $product, $user ); |
| 63 |
} |
| 64 |
|
| 65 |
return $this->matchedPricingRules[ $user->ID ][ $product->get_id() ]; |
| 66 |
} |
| 67 |
|
| 68 |
} |
| 69 |
|