rest_handle_multi_type_schema()
云策文档标注
概述
rest_handle_multi_type_schema() 是一个 WordPress REST API 函数,用于处理多类型模式中的最佳类型获取,同时提供向后兼容性支持。
关键要点
- 函数是 rest_get_best_type_for_value() 的包装器,专门处理使用无效类型的模式。
- 接受三个参数:$value(要检查的值)、$args(模式数组)和 $param(参数名,用于错误消息)。
- 返回字符串类型,表示最佳匹配类型或空字符串。
- 内置类型检查,仅允许 array、object、string、number、integer、boolean、null 等类型。
- 当模式包含无效类型时,会触发 _doing_it_wrong() 警告,但出于向后兼容性,可能仍返回无效类型。
代码示例
function rest_handle_multi_type_schema( $value, $args, $param = '' ) {
$allowed_types = array( 'array', 'object', 'string', 'number', 'integer', 'boolean', 'null' );
$invalid_types = array_diff( $args['type'], $allowed_types );
if ( $invalid_types ) {
_doing_it_wrong(
__FUNCTION__,
wp_sprintf( __( 'The "type" schema keyword for %1$s can only contain the built-in types: %2$l.' ), $param, $allowed_types ),
'5.5.0'
);
}
$best_type = rest_get_best_type_for_value( $value, $args['type'] );
if ( ! $best_type ) {
if ( ! $invalid_types ) {
return '';
}
$best_type = reset( $invalid_types );
}
return $best_type;
}注意事项
- 该函数从 WordPress 5.5.0 版本引入。
- 主要用于 rest_sanitize_value_from_schema() 和 rest_validate_value_from_schema() 等函数中。
- 开发者应确保模式类型符合内置类型列表,以避免警告和潜在错误。
原文内容
Handles getting the best type for a multi-type schema.
Description
This is a wrapper for rest_get_best_type_for_value() that handles backward compatibility for schemas that use invalid types.
Parameters
$valuemixedrequired-
The value to check.
$argsarrayrequired-
The schema array to use.
$paramstringrequired-
The parameter name, used in error messages.
Source
function rest_handle_multi_type_schema( $value, $args, $param = '' ) {
$allowed_types = array( 'array', 'object', 'string', 'number', 'integer', 'boolean', 'null' );
$invalid_types = array_diff( $args['type'], $allowed_types );
if ( $invalid_types ) {
_doing_it_wrong(
__FUNCTION__,
/* translators: 1: Parameter, 2: List of allowed types. */
wp_sprintf( __( 'The "type" schema keyword for %1$s can only contain the built-in types: %2$l.' ), $param, $allowed_types ),
'5.5.0'
);
}
$best_type = rest_get_best_type_for_value( $value, $args['type'] );
if ( ! $best_type ) {
if ( ! $invalid_types ) {
return '';
}
// Backward compatibility for previous behavior which allowed the value if there was an invalid type used.
$best_type = reset( $invalid_types );
}
return $best_type;
}
Changelog
| Version | Description |
|---|---|
| 5.5.0 | Introduced. |