namespace Automattic\WooCommerce\StoreApi\Utilities;
use Automattic\WooCommerce\Checkout\Helpers\ReserveStock;
use Automattic\WooCommerce\Enums\ProductStatus;
use Automattic\WooCommerce\Enums\ProductType;
use Automattic\WooCommerce\StoreApi\Exceptions\InvalidCartException;
use Automattic\WooCommerce\StoreApi\Exceptions\NotPurchasableException;
use Automattic\WooCommerce\StoreApi\Exceptions\OutOfStockException;
use Automattic\WooCommerce\StoreApi\Exceptions\PartialOutOfStockException;
use Automattic\WooCommerce\StoreApi\Exceptions\RouteException;
use Automattic\WooCommerce\StoreApi\Exceptions\TooManyInCartException;
use Automattic\WooCommerce\StoreApi\Utilities\ArrayUtils;
use Automattic\WooCommerce\StoreApi\Utilities\DraftOrderTrait;
use Automattic\WooCommerce\StoreApi\Utilities\NoticeHandler;
use Automattic\WooCommerce\StoreApi\Utilities\QuantityLimits;
* Woo Cart Controller class.
* Helper class to bridge the gap between the cart API and Woo core.
* Makes the cart and sessions available to a route by loading them from core.
public function load_cart() {
if ( ! did_action( 'woocommerce_load_cart_from_session' ) ) {
// Load cart from session.
$cart = $this->get_cart_instance();
$cart->cart_context = 'store-api';
* Normalizes the cart by fixing any quantity violations.
public function normalize_cart() {
$quantity_limits = new QuantityLimits();
$cart_items = $this->get_cart_items();
foreach ( $cart_items as $cart_item ) {
$normalized_qty = $quantity_limits->normalize_cart_item_quantity( $cart_item['quantity'], $cart_item );
if ( $normalized_qty !== $cart_item['quantity'] ) {
$this->set_cart_item_quantity( $cart_item['key'], $normalized_qty );
} catch ( RouteException $e ) {
// Ignore errors and continue.
* Gets the latest cart instance, and ensures totals have been calculated before returning.
public function get_cart_for_response() {
return did_action( 'woocommerce_after_calculate_totals' ) ? $this->get_cart_instance() : $this->calculate_totals();
* Recalculates the cart totals and returns the updated cart instance.
* @since 9.2.0 Calculate shipping was removed here because it's called already by calculate_totals.
public function calculate_totals() {
$cart = $this->get_cart_instance();
$cart->calculate_totals();
* Based on the core cart class but returns errors rather than rendering notices directly.
* @todo Overriding the core add_to_cart method was necessary because core outputs notices when an item is added to
* the cart. For us this would cause notices to build up and output on the store, out of context. Core would need
* refactoring to split notices out from other cart actions.
* @throws RouteException Exception if invalid data is detected.
* @param array $request Add to cart request params.
public function add_to_cart( $request ) {
$cart = $this->get_cart_instance();
$request = wp_parse_args(
$request = $this->filter_request_data( $this->parse_variation_data( $request ) );
$product = $this->get_product_for_cart( $request );
$cart_id = $cart->generate_cart_id(
$this->get_product_id( $product ),
$this->get_variation_id( $product ),
$request['cart_item_data']
$quantity_limits = new QuantityLimits();
// If quantity was not passed, it should default to the minimum allowed quantity.
if ( null === $request['quantity'] ) {
$request['quantity'] = $quantity_limits->get_add_to_cart_limits( $product )['minimum'];
$this->validate_add_to_cart( $product, $request );
$existing_cart_id = $cart->find_product_in_cart( $cart_id );
$request_quantity = wc_stock_amount( $request['quantity'] );
if ( $existing_cart_id ) {
$cart_item = $cart->cart_contents[ $existing_cart_id ];
$updated_quantity = $request_quantity + $cart_item['quantity'];
$quantity_validation = $quantity_limits->validate_cart_item_quantity( $updated_quantity, $cart_item );
if ( is_wp_error( $quantity_validation ) ) {
throw new RouteException(
esc_html( $quantity_validation->get_error_code() ),
esc_html( $quantity_validation->get_error_message() ),
$cart->set_quantity( $existing_cart_id, $updated_quantity, true );
return $existing_cart_id;
$add_to_cart_limits = $quantity_limits->get_add_to_cart_limits( $product );
if ( $add_to_cart_limits['maximum'] ) {
$request_quantity = min( $request_quantity, $add_to_cart_limits['maximum'] );
$request_quantity = max( $request_quantity, $add_to_cart_limits['minimum'] );
$request_quantity = $quantity_limits->limit_to_multiple( $request_quantity, $add_to_cart_limits['multiple_of'] );
* Filters the item being added to the cart.
* @internal Matches filter name in WooCommerce core.
* @param array $cart_item_data Array of cart item data being added to the cart.
* @param string $cart_id Id of the item in the cart.
* @return array Updated cart item data.
$cart->cart_contents[ $cart_id ] = apply_filters(
'woocommerce_add_cart_item',
$request['cart_item_data'],
'product_id' => $this->get_product_id( $product ),
'variation_id' => $this->get_variation_id( $product ),
'variation' => $request['variation'],
'quantity' => $request_quantity,
'data_hash' => wc_get_cart_item_data_hash( $product ),
* Filters the entire cart contents when the cart changes.
* @internal Matches filter name in WooCommerce core.
* @param array $cart_contents Array of all cart items.
* @return array Updated array of all cart items.
$cart->cart_contents = apply_filters( 'woocommerce_cart_contents_changed', $cart->cart_contents );
* Fires when an item is added to the cart.
* This hook fires when an item is added to the cart. This is triggered from the Store API in this context, but
* WooCommerce core add to cart events trigger the same hook.
* @internal Matches action name in WooCommerce core.
* @param string $cart_id ID of the item in the cart.
* @param integer $product_id ID of the product added to the cart.
* @param integer $request_quantity Quantity of the item added to the cart.
* @param integer $variation_id Variation ID of the product added to the cart.
* @param array $variation Array of variation data.
* @param array $cart_item_data Array of other cart item data.
'woocommerce_add_to_cart',
$this->get_product_id( $product ),
$this->get_variation_id( $product ),
$request['cart_item_data']
* Based on core `set_quantity` method, but validates if an item is sold individually first and enforces any limits in
* @throws RouteException Exception if invalid data is detected.
* @param string $item_id Cart item id.
* @param int|float $quantity Cart quantity.
public function set_cart_item_quantity( $item_id, $quantity = 1 ) {
$cart_item = $this->get_cart_item( $item_id );
if ( empty( $cart_item ) ) {
throw new RouteException( 'woocommerce_rest_cart_invalid_key', esc_html__( 'Cart item does not exist.', 'woocommerce' ), 409 );
$product = $cart_item['data'] ?? false;
if ( ! $product instanceof \WC_Product ) {
throw new RouteException( 'woocommerce_rest_cart_invalid_product', esc_html__( 'Cart item is invalid.', 'woocommerce' ), 404 );
$quantity_validation = ( new QuantityLimits() )->validate_cart_item_quantity( $quantity, $cart_item );
if ( is_wp_error( $quantity_validation ) ) {
throw new RouteException( $quantity_validation->get_error_code(), $quantity_validation->get_error_message(), 400 ); // phpcs:ignore WordPress.Security.EscapeOutput.ExceptionNotEscaped
$cart = $this->get_cart_instance();
$cart->set_quantity( $item_id, $quantity );
* Validate all items in the cart and check for errors.
* @throws RouteException Exception if invalid data is detected.
* @param \WC_Product $product Product object associated with the cart item.
* @param array $request Add to cart request params.
public function validate_add_to_cart( \WC_Product $product, $request ) {
if ( ! $product->is_purchasable() ) {
$this->throw_default_product_exception( $product );
if ( floatval( $request['quantity'] ) <= 0 ) {
throw new RouteException(
'woocommerce_rest_product_invalid_quantity',
/* translators: %s: product name */
esc_html__( 'You cannot add "%s" with a quantity less than or equal to 0 to the cart.', 'woocommerce' ),
esc_html( $product->get_name() )
if ( ! $product->is_in_stock() ) {
throw new RouteException(
'woocommerce_rest_product_out_of_stock',
/* translators: %s: product name */
esc_html__( 'You cannot add "%s" to the cart because the product is out of stock.', 'woocommerce' ),
if ( $product->managing_stock() && ! $product->backorders_allowed() ) {
$request_quantity = wc_stock_amount( $request['quantity'] );
$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 + $request_quantity ) {
throw new RouteException(
'woocommerce_rest_product_partially_out_of_stock',
/* translators: 1: product name 2: quantity in stock */
esc_html__( 'You cannot add that amount of "%1$s" to the cart because there is not enough stock (%2$s remaining).', 'woocommerce' ),
wc_format_stock_quantity_for_display( $qty_remaining, $product )
* Filters if an item being added to the cart passed validation checks.
* Allow 3rd parties to validate if an item can be added to the cart. This is a legacy hook from Woo core.
* This filter will be deprecated because it encourages usage of wc_add_notice. For the API we need to capture
* notices and convert to exceptions instead.
* @param boolean $passed_validation True if the item passed validation.
* @param integer $product_id Product ID being validated.
* @param integer $quantity Quantity added to the cart.
* @param integer $variation_id Variation ID being added to the cart.
* @param array $variation Variation data.
$passed_validation = apply_filters(
'woocommerce_add_to_cart_validation',
$this->get_product_id( $product ),
$this->get_variation_id( $product ),
$request['cart_item_data']
if ( ! $passed_validation ) {
// Validation did not pass - see if an error notice was thrown.
NoticeHandler::convert_notices_to_exceptions( 'woocommerce_rest_add_to_cart_error' );
// If no notice was thrown, throw the default notice instead.
$this->throw_default_product_exception( $product );
* Fires during validation when adding an item to the cart via the Store API.
* @param \WC_Product $product Product object being added to the cart.
* @param array $request Add to cart request params including id, quantity, and variation attributes.
* @deprecated 7.1.0 Use woocommerce_store_api_validate_add_to_cart instead.
'wooocommerce_store_api_validate_add_to_cart',
'woocommerce_store_api_validate_add_to_cart',
'This action was deprecated in WooCommerce Blocks version 7.1.0. Please use woocommerce_store_api_validate_add_to_cart instead.'
* Fires during validation when adding an item to the cart via the Store API.
* Fire action to validate add to cart. Functions hooking into this should throw an \Exception to prevent
* add to cart from happening.
* @param \WC_Product $product Product object being added to the cart.
* @param array $request Add to cart request params including id, quantity, and variation attributes.
do_action( 'woocommerce_store_api_validate_add_to_cart', $product, $request );
* Generates the error message for out of stock products and adds product names to it.
* @param string $singular The message to use when only one product is in the list.
* @param string $plural The message to use when more than one product is in the list.
* @param array $items The list of cart items whose names should be inserted into the message.
* @returns string The translated and correctly pluralised message.
private function add_product_names_to_message( $singular, $plural, $items ) {
$product_names = wc_list_pluck( $items, 'getProductName' );
$message = ( count( $items ) > 1 ) ? $plural : $singular;
ArrayUtils::natural_language_join( $product_names, true )
* Takes a string describing the type of stock extension, whether there is a single product or multiple products
* causing this exception and returns an appropriate error message.
* @param string $exception_type The type of exception encountered.
* @param string $singular_or_plural Whether to get the error message for a single product or multiple.
private function get_error_message_for_stock_exception_type( $exception_type, $singular_or_plural ) {
$stock_error_messages = [
/* translators: %s: product name. */
'singular' => esc_html__(
'%s is out of stock and cannot be purchased. Please remove it from your cart.',
/* translators: %s: product names. */
'%s are out of stock and cannot be purchased. Please remove them from your cart.',
/* translators: %s: product name. */
'singular' => esc_html__(
'%s cannot be purchased. Please remove it from your cart.',
/* translators: %s: product names. */
'%s cannot be purchased. Please remove them from your cart.',
/* translators: %s: product names. */
'singular' => esc_html__(
'There are too many %s in the cart. Only 1 can be purchased. Please reduce the quantity in your cart.',
/* translators: %s: product names. */
'There are too many %s in the cart. Only 1 of each can be purchased. Please reduce the quantities in your cart.',
'partial_out_of_stock' => [
/* translators: %s: product names. */
'singular' => esc_html__(
'There is not enough %s in stock. Please reduce the quantity in your cart.',
/* translators: %s: product names. */
'There are not enough %s in stock. Please reduce the quantities in your cart.',
isset( $stock_error_messages[ $exception_type ] ) &&
isset( $stock_error_messages[ $exception_type ][ $singular_or_plural ] )
return $stock_error_messages[ $exception_type ][ $singular_or_plural ];
return esc_html__( 'There was an error with an item in your cart.', 'woocommerce' );
* Validate cart and check for errors.
* @throws InvalidCartException Exception if invalid data is detected in the cart.
public function validate_cart() {
$this->validate_cart_items();
$this->validate_cart_coupons();
$cart = $this->get_cart_instance();
$cart_errors = new WP_Error();
* Fires an action to validate the cart.
* Functions hooking into this should add custom errors using the provided WP_Error instance.
* @example See docs/examples/validate-cart.md
* @param \WP_Error $errors WP_Error object.
* @param \WC_Cart $cart Cart object.
do_action( 'woocommerce_store_api_cart_errors', $cart_errors, $cart );
if ( $cart_errors->has_errors() ) {
throw new InvalidCartException(
'woocommerce_cart_error',