函数文档

rest_find_any_matching_schema()

💡 云策文档标注

概述

rest_find_any_matching_schema() 函数用于在“anyOf”模式数组中查找与给定值匹配的模式。它通过遍历模式并验证值来实现,返回匹配的模式或 WP_Error 实例。

关键要点

  • 函数接受三个参数:$value(要验证的值)、$args(模式数组)、$param(参数名,用于错误消息)。
  • 遍历 $args['anyOf'] 中的每个模式,如果模式未定义 type 但 $args 有 type,则继承 type。
  • 使用 rest_validate_value_from_schema() 验证值,如果验证成功则返回匹配的模式。
  • 如果所有模式都不匹配,则返回 rest_get_combining_operation_error() 生成的 WP_Error 实例。
  • 函数在 WordPress 5.6.0 版本中引入。

代码示例

function rest_find_any_matching_schema( $value, $args, $param ) {
	$errors = array();

	foreach ( $args['anyOf'] as $index => $schema ) {
		if ( ! isset( $schema['type'] ) && isset( $args['type'] ) ) {
			$schema['type'] = $args['type'];
		}

		$is_valid = rest_validate_value_from_schema( $value, $schema, $param );
		if ( ! is_wp_error( $is_valid ) ) {
			return $schema;
		}

		$errors[] = array(
			'error_object' => $is_valid,
			'schema'       => $schema,
			'index'        => $index,
		);
	}

	return rest_get_combining_operation_error( $value, $param, $errors );
}

注意事项

  • 函数依赖于 rest_validate_value_from_schema() 进行验证,确保相关函数可用。
  • 错误处理通过 rest_get_combining_operation_error() 聚合多个验证错误。
  • 相关函数包括 rest_filter_response_by_context()、rest_sanitize_value_from_schema() 等,用于 REST API 数据处理。

📄 原文内容

Finds the matching schema among the “anyOf” schemas.

Parameters

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

Return

array|WP_Error The matching schema or WP_Error instance if all schemas do not match.

Source

function rest_find_any_matching_schema( $value, $args, $param ) {
	$errors = array();

	foreach ( $args['anyOf'] as $index => $schema ) {
		if ( ! isset( $schema['type'] ) && isset( $args['type'] ) ) {
			$schema['type'] = $args['type'];
		}

		$is_valid = rest_validate_value_from_schema( $value, $schema, $param );
		if ( ! is_wp_error( $is_valid ) ) {
			return $schema;
		}

		$errors[] = array(
			'error_object' => $is_valid,
			'schema'       => $schema,
			'index'        => $index,
		);
	}

	return rest_get_combining_operation_error( $value, $param, $errors );
}

Changelog

Version Description
5.6.0 Introduced.