REST API: Check required properties are provided when validating an object.

Previously, the WP_REST_Request object validated that top-level properties were defined, but this did not extend to those object's required properties. This adds validation to rest_validate_value_from_schema() directly.

Both the v3 and v4 JSON Schema syntax for required properties is supported.

Props sorenbronsted.
Fixes #48818.

Built from https://develop.svn.wordpress.org/trunk@47809


git-svn-id: http://core.svn.wordpress.org/trunk@47585 1a063a9b-81f0-0310-95a4-ce76da25c4cd
This commit is contained in:
TimothyBlynJacobs 2020-05-16 18:44:09 +00:00
parent 7932193708
commit 26bda18a23
2 changed files with 17 additions and 1 deletions

View File

@ -1284,6 +1284,22 @@ function rest_validate_value_from_schema( $value, $args, $param = '' ) {
return new WP_Error( 'rest_invalid_param', sprintf( __( '%1$s is not of type %2$s.' ), $param, 'object' ) );
}
if ( isset( $args['required'] ) && is_array( $args['required'] ) ) { // schema version 4
foreach ( $args['required'] as $name ) {
if ( ! array_key_exists( $name, $value ) ) {
/* translators: 1: Property of an object, 2: Parameter. */
return new WP_Error( 'rest_property_required', sprintf( __( '%1$s is a required property of %2$s.' ), $name, $param ) );
}
}
} elseif ( isset( $args['properties'] ) ) { // schema version 3
foreach ( $args['properties'] as $name => $property ) {
if ( isset( $property['required'] ) && true === $property['required'] && ! array_key_exists( $name, $value ) ) {
/* translators: 1: Property of an object, 2: Parameter. */
return new WP_Error( 'rest_property_required', sprintf( __( '%1$s is a required property of %2$s.' ), $name, $param ) );
}
}
}
foreach ( $value as $property => $v ) {
if ( isset( $args['properties'][ $property ] ) ) {
$is_valid = rest_validate_value_from_schema( $v, $args['properties'][ $property ], $param . '[' . $property . ']' );

View File

@ -13,7 +13,7 @@
*
* @global string $wp_version
*/
$wp_version = '5.5-alpha-47808';
$wp_version = '5.5-alpha-47809';
/**
* Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema.