| 1 |
<?php |
| 2 |
|
| 3 |
namespace TierPricingTable\Frontend; |
| 4 |
|
| 5 |
use TierPricingTable\Settings\Settings ; |
| 6 |
use TierPricingTable\PriceManager ; |
| 7 |
use WC_Product ; |
| 8 |
/** |
| 9 |
* Class CartPriceManager |
| 10 |
* |
| 11 |
* @package TierPricingTable |
| 12 |
*/ |
| 13 |
class CartPriceManager |
| 14 |
{ |
| 15 |
/** |
| 16 |
* @var Settings |
| 17 |
*/ |
| 18 |
private $settings ; |
| 19 |
/** |
| 20 |
* CatalogPriceManager constructor. |
| 21 |
* |
| 22 |
* @param Settings $settings |
| 23 |
*/ |
| 24 |
public function __construct( Settings $settings ) |
| 25 |
{ |
| 26 |
$this->settings = $settings; |
| 27 |
$this->hooks(); |
| 28 |
} |
| 29 |
|
| 30 |
protected function hooks() |
| 31 |
{ |
| 32 |
// Calculate product price in cart by pricing rules |
| 33 |
add_action( |
| 34 |
'woocommerce_before_calculate_totals', |
| 35 |
[ $this, 'calculateTotals' ], |
| 36 |
10, |
| 37 |
1 |
| 38 |
); |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Calculate price by quantity rules |
| 43 |
* |
| 44 |
* @param WC_Cart $cart |
| 45 |
*/ |
| 46 |
public function calculateTotals( $cart ) |
| 47 |
{ |
| 48 |
if ( !empty($cart->cart_contents) ) { |
| 49 |
foreach ( $cart->cart_contents as $key => $cart_item ) { |
| 50 |
|
| 51 |
if ( $cart_item['data'] instanceof WC_Product ) { |
| 52 |
$product_id = ( !empty($cart_item['variation_id']) ? $cart_item['variation_id'] : $cart_item['product_id'] ); |
| 53 |
$new_price = PriceManager::getPriceByRules( $cart_item['quantity'], $product_id ); |
| 54 |
if ( $new_price !== false ) { |
| 55 |
$cart_item['data']->set_price( $new_price ); |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
} |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
} |