Automattic\WooCommerce\StoreApi\Utilities

OrderController::validate_address_fields()protectedWC 1.0

Check all required address fields are set and return errors if not.

Method of the class: OrderController{}

No Hooks.

Return

null. Nothing (null).

Usage

// protected - for code of main (parent) or child class
$result = $this->validate_address_fields( $order, $address_type, $errors );
$order(\WC_Order) (required)
Order object.
$address_type(string) (required)
billing or shipping address, used in error messages.
$errors(\WP_Error) (required)
Error object.

OrderController::validate_address_fields() code WC 9.3.3

protected function validate_address_fields( \WC_Order $order, $address_type, \WP_Error $errors ) {
	$all_locales    = wc()->countries->get_country_locale();
	$address        = $order->get_address( $address_type );
	$current_locale = isset( $all_locales[ $address['country'] ] ) ? $all_locales[ $address['country'] ] : array();

	foreach ( $all_locales['default'] as $key => $value ) {
		$default_value          = empty( $current_locale[ $key ] ) ? [] : $current_locale[ $key ];
		$current_locale[ $key ] = wp_parse_args( $default_value, $value );
	}

	$additional_fields = $this->additional_fields_controller->get_all_fields_from_object( $order, $address_type );

	$address = array_merge( $address, $additional_fields );

	foreach ( $current_locale as $address_field_key => $address_field ) {
		if ( empty( $address[ $address_field_key ] ) && $address_field['required'] ) {
			/* translators: %s Field label. */
			$errors->add( $address_type, sprintf( __( '%s is required', 'woocommerce' ), $address_field['label'] ), $address_field_key );
		}
	}

	// Validate additional fields.
	$result = $this->additional_fields_controller->validate_fields_for_location( $address, 'address', $address_type );

	if ( $result->has_errors() ) {
		// Add errors to main error object but ensure they maintain the billing/shipping error code.
		foreach ( $result->get_error_codes() as $code ) {
			$errors->add( $address_type, $result->get_error_message( $code ), $code );
		}
	}
}