Automattic\WooCommerce\Internal\RestApi\Routes\V4\Settings\Emails\Schema

EmailsSettingsSchema::validate_field_valueprivateWC 1.0

Validate field value.

Method of the class: EmailsSettingsSchema{}

No Hooks.

Returns

true|WP_Error. True if valid, WP_Error otherwise.

Usage

// private - for code of main (parent) class only
$result = $this->validate_field_value( $key, $value, $field );
$key(string) (required)
Field key.
$value(mixed) (required)
Sanitized value.
$field(array) (required)
Field definition.

EmailsSettingsSchema::validate_field_value() code WC 10.4.3

private function validate_field_value( string $key, $value, array $field ) {
	$field_type = $field['type'] ?? 'text';

	// Validate email format.
	if ( 'email' === $field_type && ! empty( $value ) && ! is_email( $value ) ) {
		return new WP_Error(
			'rest_invalid_param',
			sprintf(
				/* translators: %s: field key */
				__( 'Invalid email format for %s.', 'woocommerce' ),
				$key
			),
			array( 'status' => 400 )
		);
	}

	// Validate select options.
	if ( 'select' === $field_type && ! empty( $field['options'] ) ) {
		if ( ! array_key_exists( $value, $field['options'] ) && '' !== $value ) {
			return new WP_Error(
				'rest_invalid_param',
				sprintf(
					/* translators: 1: field key, 2: valid options */
					__( 'Invalid value for %1$s. Valid options: %2$s', 'woocommerce' ),
					$key,
					implode( ', ', array_keys( $field['options'] ) )
				),
				array( 'status' => 400 )
			);
		}
	}

	// Validate multiselect options.
	if ( 'multiselect' === $field_type && ! empty( $field['options'] ) ) {
		if ( is_array( $value ) ) {
			foreach ( $value as $v ) {
				if ( ! array_key_exists( $v, $field['options'] ) ) {
					return new WP_Error(
						'rest_invalid_param',
						sprintf(
							/* translators: 1: field key, 2: invalid value */
							__( 'Invalid option "%2$s" for %1$s.', 'woocommerce' ),
							$key,
							$v
						),
						array( 'status' => 400 )
					);
				}
			}
		}
	}

	return true;
}