Automattic\WooCommerce\StoreApi\Utilities

AgenticCheckoutUtils::add_items_to_cartpublic staticWC 1.0

Add items to cart from request.

Method of the class: AgenticCheckoutUtils{}

No Hooks.

Returns

Error|null. Returns error response on failure, null on success.

Usage

$result = AgenticCheckoutUtils::add_items_to_cart( $items, $cart_controller, $messages );
$items(array) (required)
Items array from request.
$cart_controller(CartController) (required)
Cart controller instance.
$messages(Messages) (required)
Error messages instance.

AgenticCheckoutUtils::add_items_to_cart() code WC 10.4.3

public static function add_items_to_cart( $items, $cart_controller, $messages ) {
	foreach ( $items as $item_index => $item ) {
		if ( ! ctype_digit( $item['id'] ) ) {
			return AgenticError::invalid_request(
				'invalid_product_id',
				__( 'Product ID must be numeric.', 'woocommerce' ),
				'$.items[' . $item_index . '].id'
			);
		}

		$product_id = (int) $item['id'];
		$quantity   = (int) $item['quantity'];

		try {
			$cart_controller->add_to_cart(
				[
					'id'       => $product_id,
					'quantity' => $quantity,
				]
			);
		} catch ( RouteException $exception ) {
			$message       = wp_specialchars_decode( $exception->getMessage(), ENT_QUOTES );
			$param         = '$.items[' . $item_index . ']';
			$message_error = null;

			// Map WooCommerce error codes to Agentic Commerce Protocol error codes.
			switch ( $exception->getErrorCode() ) {
				case 'woocommerce_rest_product_out_of_stock':
				case 'woocommerce_rest_product_partially_out_of_stock':
					$message_error = MessageError::out_of_stock( $message, $param );
					break;
			}

			if ( null !== $message_error ) {
				$messages->add( $message_error );
			} else {
				// The error code is generally applicable only to MessageErrors, but we can use it here as well.
				return AgenticError::invalid_request( ErrorCode::INVALID, $message, $param );
			}
		}
	}

	return null;
}