函数文档

rest_validate_enum()

💡 云策文档标注

概述

rest_validate_enum() 是 WordPress REST API 中的一个验证函数,用于检查给定值是否为 JSON Schema "enum" 的成员。它基于提供的 schema 参数进行验证,返回 true 或 WP_Error 实例。

关键要点

  • 函数用途:验证值是否在 JSON Schema 的枚举列表中,遵循 REST API 的验证规范。
  • 参数说明:接受三个参数:$value(要验证的值)、$args(schema 数组)、$param(参数名,用于错误消息)。
  • 返回值:如果值在枚举中返回 true,否则返回 WP_Error 实例,包含错误代码和本地化消息。
  • 内部逻辑:先使用 rest_sanitize_value_from_schema() 清理值,再通过 rest_are_values_equal() 比较枚举成员,处理标量和非标量值的编码。
  • 注意事项:避免在属性接受数组值时使用枚举,否则可能导致验证失败。

代码示例

array(
    'description' => 'Testing',
    'context'     => array( 'view', 'edit' ),
    'enum'        => array( 'first', 'second', 'third' ),
    'type'        => 'array',
    'items'       => array(
        'type' => 'string',
    ),
    'default'     => array( 'first', 'second' ),
    'required'    => false,
)

📄 原文内容

Validates that the given value is a member of the JSON Schema “enum”.

Parameters

$valuemixedrequired
The value to validate.
$argsarrayrequired
The schema array to use.
$paramstringrequired
The parameter name, used in error messages.

Return

true|WP_Error True if the “enum” contains the value or a WP_Error instance otherwise.

Source

function rest_validate_enum( $value, $args, $param ) {
	$sanitized_value = rest_sanitize_value_from_schema( $value, $args, $param );
	if ( is_wp_error( $sanitized_value ) ) {
		return $sanitized_value;
	}

	foreach ( $args['enum'] as $enum_value ) {
		if ( rest_are_values_equal( $sanitized_value, $enum_value ) ) {
			return true;
		}
	}

	$encoded_enum_values = array();
	foreach ( $args['enum'] as $enum_value ) {
		$encoded_enum_values[] = is_scalar( $enum_value ) ? $enum_value : wp_json_encode( $enum_value );
	}

	if ( count( $encoded_enum_values ) === 1 ) {
		/* translators: 1: Parameter, 2: Valid values. */
		return new WP_Error( 'rest_not_in_enum', wp_sprintf( __( '%1$s is not %2$s.' ), $param, $encoded_enum_values[0] ) );
	}

	/* translators: 1: Parameter, 2: List of valid values. */
	return new WP_Error( 'rest_not_in_enum', wp_sprintf( __( '%1$s is not one of %2$l.' ), $param, $encoded_enum_values ) );
}

Changelog

Version Description
5.7.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    NOTE: Do not provide enums if the property accepts array values. The example below will fail.

    array(
    	'description' => 'Testing',
    	'context'     => array( 'view', 'edit' ),
    	'enum'        => array( 'first', 'second', 'third' ),
    	'type'        => 'array',
    	'items'       => array(
    		'type' => 'string',
    	),
    	'default'     => array( 'first', 'second' ),
    	'required'    => false,
    )