Automattic\WooCommerce\StoreApi\Utilities

OrderController::validate_addresses()protectedWC 1.0

Validates customer address data based on the locale to ensure required fields are set.

Method of the class: OrderController{}

No Hooks.

Return

null. Nothing (null).

Usage

// protected - for code of main (parent) or child class
$result = $this->validate_addresses( $order );
$order(\WC_Order) (required)
Order object.

OrderController::validate_addresses() code WC 8.6.1

protected function validate_addresses( \WC_Order $order ) {
	$errors           = new \WP_Error();
	$needs_shipping   = wc()->cart->needs_shipping();
	$billing_country  = $order->get_billing_country();
	$shipping_country = $order->get_shipping_country();

	if ( $needs_shipping && ! $this->validate_allowed_country( $shipping_country, (array) wc()->countries->get_shipping_countries() ) ) {
		throw new RouteException(
			'woocommerce_rest_invalid_address_country',
			sprintf(
				/* translators: %s country code. */
				__( 'Sorry, we do not ship orders to the provided country (%s)', 'woocommerce' ),
				$shipping_country
			),
			400,
			array(
				'allowed_countries' => array_keys( wc()->countries->get_shipping_countries() ),
			)
		);
	}

	if ( ! $this->validate_allowed_country( $billing_country, (array) wc()->countries->get_allowed_countries() ) ) {
		throw new RouteException(
			'woocommerce_rest_invalid_address_country',
			sprintf(
				/* translators: %s country code. */
				__( 'Sorry, we do not allow orders from the provided country (%s)', 'woocommerce' ),
				$billing_country
			),
			400,
			array(
				'allowed_countries' => array_keys( wc()->countries->get_allowed_countries() ),
			)
		);
	}

	if ( $needs_shipping ) {
		$this->validate_address_fields( $order, 'shipping', $errors );
	}
	$this->validate_address_fields( $order, 'billing', $errors );

	if ( ! $errors->has_errors() ) {
		return;
	}

	$errors_by_code = array();
	$error_codes    = $errors->get_error_codes();
	foreach ( $error_codes as $code ) {
		$errors_by_code[ $code ] = $errors->get_error_messages( $code );
	}

	// Surface errors from first code.
	foreach ( $errors_by_code as $code => $error_messages ) {
		throw new RouteException(
			'woocommerce_rest_invalid_address',
			sprintf(
				/* translators: %s Address type. */
				__( 'There was a problem with the provided %s:', 'woocommerce' ) . ' ' . implode( ', ', $error_messages ),
				'shipping' === $code ? __( 'shipping address', 'woocommerce' ) : __( 'billing address', 'woocommerce' )
			),
			400,
			array(
				'errors' => $errors_by_code,
			)
		);
	}
}