Automattic\WooCommerce\StoreApi\Utilities

OrderController::validate_coupons()protectedWC 1.0

Validate coupons applied to the order and remove those that are not valid.

Метод класса: OrderController{}

Хуков нет.

Возвращает

null. Ничего (null).

Использование

// protected - в коде основоного (родительского) или дочернего класса
$result = $this->validate_coupons( $order );
$order(\WC_Order) (обязательный)
Order object.

Код OrderController::validate_coupons() WC 8.7.0

protected function validate_coupons( \WC_Order $order ) {
	$coupon_codes  = $order->get_coupon_codes();
	$coupons       = array_filter( array_map( array( $this, 'get_coupon' ), $coupon_codes ) );
	$validators    = array( 'validate_coupon_email_restriction', 'validate_coupon_usage_limit' );
	$coupon_errors = array();

	foreach ( $coupons as $coupon ) {
		try {
			array_walk(
				$validators,
				function( $validator, $index, $params ) {
					call_user_func_array( array( $this, $validator ), $params );
				},
				array( $coupon, $order )
			);
		} catch ( Exception $error ) {
			$coupon_errors[ $coupon->get_code() ] = $error->getMessage();
		}
	}

	if ( $coupon_errors ) {
		// Remove all coupons that were not valid.
		foreach ( $coupon_errors as $coupon_code => $message ) {
			wc()->cart->remove_coupon( $coupon_code );
		}

		// Recalculate totals.
		wc()->cart->calculate_totals();

		// Re-sync order with cart.
		$this->update_order_from_cart( $order );

		// Return exception so customer can review before payment.
		if ( 1 === count( $coupon_errors ) ) {
			throw new RouteException(
				'woocommerce_rest_cart_coupon_errors',
				sprintf(
					/* translators: %1$s Coupon codes, %2$s Reason */
					__( '"%1$s" was removed from the cart. %2$s', 'woocommerce' ),
					array_keys( $coupon_errors )[0],
					array_values( $coupon_errors )[0],
				),
				409,
				array(
					'removed_coupons' => $coupon_errors,
				)
			);
		} else {
			throw new RouteException(
				'woocommerce_rest_cart_coupon_errors',
				sprintf(
					/* translators: %s Coupon codes. */
					__( 'Invalid coupons were removed from the cart: "%s"', 'woocommerce' ),
					implode( '", "', array_keys( $coupon_errors ) )
				),
				409,
				array(
					'removed_coupons' => $coupon_errors,
				)
			);
		}
	}
}