| 1 |
<?php namespace TierPricingTable\Addons\MinQuantity; |
| 2 |
|
| 3 |
use TierPricingTable\PriceManager; |
| 4 |
use WC_Product; |
| 5 |
|
| 6 |
class StoreApiValidation { |
| 7 |
|
| 8 |
public function run() { |
| 9 |
add_action( 'woocommerce_store_api_cart_errors', array( $this, 'validateCart' ) ); |
| 10 |
} |
| 11 |
|
| 12 |
public function validateCart( $errorContext ) { |
| 13 |
$cart = wc()->cart; |
| 14 |
if ( ! $cart ) { |
| 15 |
return; |
| 16 |
} |
| 17 |
|
| 18 |
$parentQuantities = array(); |
| 19 |
|
| 20 |
foreach ( $cart->get_cart_contents() as $cartItem ) { |
| 21 |
if ( $cartItem['data'] instanceof WC_Product ) { |
| 22 |
$itemPricingRule = PriceManager::getPricingRule( $cartItem['data']->get_id() ); |
| 23 |
$itemMin = $itemPricingRule->getMinimum(); |
| 24 |
if ( $itemMin && $cartItem['quantity'] < $itemMin ) { |
| 25 |
$errorContext->add( |
| 26 |
'tier_pricing_table_min_qty', |
| 27 |
sprintf( __( 'Minimum quantity for %1$s is %2$s.', 'tier-pricing-table' ), |
| 28 |
$cartItem['data']->get_name(), $itemMin ) |
| 29 |
); |
| 30 |
} |
| 31 |
|
| 32 |
$parentId = $cartItem['data']->get_parent_id(); |
| 33 |
if ( $parentId ) { |
| 34 |
if ( ! isset( $parentQuantities[ $parentId ] ) ) { |
| 35 |
$parentQuantities[ $parentId ] = 0; |
| 36 |
} |
| 37 |
$parentQuantities[ $parentId ] += $cartItem['quantity']; |
| 38 |
} |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
foreach ( $parentQuantities as $parentId => $qty ) { |
| 43 |
$pricingRule = PriceManager::getPricingRule( $parentId ); |
| 44 |
if ( $pricingRule->isMixAndMatchMinQuantity() && $pricingRule->getMinimum() ) { |
| 45 |
if ( $qty < $pricingRule->getMinimum() ) { |
| 46 |
$product = wc_get_product( $parentId ); |
| 47 |
$errorContext->add( |
| 48 |
'tier_pricing_table_mix_match_min_qty', |
| 49 |
sprintf( __( 'You need to order at least %1$s items of %2$s to meet the minimum order quantity.', 'tier-pricing-table' ), |
| 50 |
$pricingRule->getMinimum(), $product ? $product->get_name() : '' ) |
| 51 |
); |
| 52 |
} |
| 53 |
} |
| 54 |
} |
| 55 |
} |
| 56 |
} |
| 57 |
|