WordPress at Your Fingertips
function is not described

WC_REST_Orders_Controller::calculate_coupons() protected WC 1.0

Calculate coupons.

{} It's a method of the class: WC_REST_Orders_Controller{}

No Hooks.

Return

true|false.

Usage

// protected - for code of main (parent) or child class
$result = $this->calculate_coupons( $request, $order );
$request(WP_REST_Request) (required)
Request object.
$order(WC_Order) (required)
Order data.

Code of WC_REST_Orders_Controller::calculate_coupons() WC 5.6.0

protected function calculate_coupons( $request, $order ) {
	if ( ! isset( $request['coupon_lines'] ) ) {
		return false;
	}

	// Validate input and at the same time store the processed coupon codes to apply.

	$coupon_codes = array();
	$discounts    = new WC_Discounts( $order );

	$current_order_coupons      = array_values( $order->get_coupons() );
	$current_order_coupon_codes = array_map(
		function( $coupon ) {
			return $coupon->get_code();
		},
		$current_order_coupons
	);

	foreach ( $request['coupon_lines'] as $item ) {
		if ( ! empty( $item['id'] ) ) {
			throw new WC_REST_Exception( 'woocommerce_rest_coupon_item_id_readonly', __( 'Coupon item ID is readonly.', 'woocommerce' ), 400 );
		}

		if ( empty( $item['code'] ) ) {
			throw new WC_REST_Exception( 'woocommerce_rest_invalid_coupon', __( 'Coupon code is required.', 'woocommerce' ), 400 );
		}

		$coupon_code = wc_format_coupon_code( wc_clean( $item['code'] ) );
		$coupon      = new WC_Coupon( $coupon_code );

		// Skip check if the coupon is already applied to the order, as this could wrongly throw an error for single-use coupons.
		if ( ! in_array( $coupon_code, $current_order_coupon_codes, true ) ) {
			$check_result = $discounts->is_coupon_valid( $coupon );
			if ( is_wp_error( $check_result ) ) {
				throw new WC_REST_Exception( 'woocommerce_rest_' . $check_result->get_error_code(), $check_result->get_error_message(), 400 );
			}
		}

		$coupon_codes[] = $coupon_code;
	}

	// Remove all coupons first to ensure calculation is correct.
	foreach ( $order->get_items( 'coupon' ) as $existing_coupon ) {
		$order->remove_coupon( $existing_coupon->get_code() );
	}

	// Apply the coupons.
	foreach ( $coupon_codes as $new_coupon ) {
		$results = $order->apply_coupon( $new_coupon );

		if ( is_wp_error( $results ) ) {
			throw new WC_REST_Exception( 'woocommerce_rest_' . $results->get_error_code(), $results->get_error_message(), 400 );
		}
	}

	return true;
}