函数文档

rest_get_best_type_for_value()

💡 云策文档标注

概述

rest_get_best_type_for_value() 函数用于根据给定值和可能的类型列表,确定最佳匹配的类型。它通过内部定义的检查数组来验证值是否符合特定类型,并优先处理空字符串情况。

关键要点

  • 函数接受两个参数:$value(要检查的值)和 $types(可能的类型列表)。
  • 返回最佳匹配的类型字符串,若无匹配则返回空字符串。
  • 内部使用静态数组 $checks 来映射类型到对应的检查函数。
  • 特殊处理空字符串:如果值空且类型列表包含 'string',则优先返回 'string'。
  • 函数在 WordPress 5.5.0 版本中引入。

代码示例

static $checks = array(
    'array'   => 'rest_is_array',
    'object'  => 'rest_is_object',
    'integer' => 'rest_is_integer',
    'number'  => 'is_numeric',
    'boolean' => 'rest_is_boolean',
    'string'  => 'is_string',
    'null'    => 'is_null',
);

注意事项

  • 函数主要用于 REST API 中处理多类型模式,如 rest_handle_multi_type_schema() 所使用。
  • 检查数组中的函数名如 rest_is_array 等是 WordPress 内部函数,需确保其可用性。

📄 原文内容

Gets the best type for a value.

Parameters

$valuemixedrequired
The value to check.
$typesstring[]required
The list of possible types.

Return

string The best matching type, an empty string if no types match.

Source

function rest_get_best_type_for_value( $value, $types ) {
	static $checks = array(
		'array'   => 'rest_is_array',
		'object'  => 'rest_is_object',
		'integer' => 'rest_is_integer',
		'number'  => 'is_numeric',
		'boolean' => 'rest_is_boolean',
		'string'  => 'is_string',
		'null'    => 'is_null',
	);

	/*
	 * Both arrays and objects allow empty strings to be converted to their types.
	 * But the best answer for this type is a string.
	 */
	if ( '' === $value && in_array( 'string', $types, true ) ) {
		return 'string';
	}

	foreach ( $types as $type ) {
		if ( isset( $checks[ $type ] ) && $checks[ $type ]( $value ) ) {
			return $type;
		}
	}

	return '';
}

Changelog

Version Description
5.5.0 Introduced.