Automattic\WooCommerce\StoreApi\Utilities

CartController::validate_cart_item()publicWC 1.0

Validates an existing cart item and returns any errors.

Method of the class: CartController{}

Return

null. Nothing (null).

Usage

$CartController = new CartController();
$CartController->validate_cart_item( $cart_item );
$cart_item(array) (required)
Cart item array.

CartController::validate_cart_item() code WC 9.3.3

public function validate_cart_item( $cart_item ) {
	$product = $cart_item['data'];

	if ( ! $product instanceof \WC_Product ) {
		return;
	}

	if ( ! $product->is_purchasable() ) {
		throw new NotPurchasableException(
			'woocommerce_rest_product_not_purchasable',
			$product->get_name()
		);
	}

	if ( $product->is_sold_individually() && $cart_item['quantity'] > 1 ) {
		throw new TooManyInCartException(
			'woocommerce_rest_product_too_many_in_cart',
			$product->get_name()
		);
	}

	if ( ! $product->is_in_stock() ) {
		throw new OutOfStockException(
			'woocommerce_rest_product_out_of_stock',
			$product->get_name()
		);
	}

	if ( $product->managing_stock() && ! $product->backorders_allowed() ) {
		$qty_remaining = $this->get_remaining_stock_for_product( $product );
		$qty_in_cart   = $this->get_product_quantity_in_cart( $product );

		if ( $qty_remaining < $qty_in_cart ) {
			throw new PartialOutOfStockException(
				'woocommerce_rest_product_partially_out_of_stock',
				$product->get_name()
			);
		}
	}

	/**
	 * Fire action to validate add to cart. Functions hooking into this should throw an \Exception to prevent
	 * add to cart from occurring.
	 *
	 * @param \WC_Product $product Product object being added to the cart.
	 * @param array       $cart_item Cart item array.
	 * @deprecated 7.1.0 Use woocommerce_store_api_validate_cart_item instead.
	 */
	wc_do_deprecated_action(
		'wooocommerce_store_api_validate_cart_item',
		array(
			$product,
			$cart_item,
		),
		'7.1.0',
		'woocommerce_store_api_validate_cart_item',
		'This action was deprecated in WooCommerce Blocks version 7.1.0. Please use woocommerce_store_api_validate_cart_item instead.'
	);

	/**
	 * Fire action to validate add to cart. Functions hooking into this should throw an \Exception to prevent
	 * add to cart from occurring.
	 *
	 * @since 7.1.0
	 *
	 * @param \WC_Product $product Product object being added to the cart.
	 * @param array       $cart_item Cart item array.
	 */
	do_action( 'woocommerce_store_api_validate_cart_item', $product, $cart_item );
}