REST API: Correct enum validation for numeric values.

When validating `enum` values as `integer` or `number`, consider a number with a zero fractional part to be equivalent to an integer of the same value.

In `rest_are_values_equal()`, when comparing two values of type `int` or `float` (in any combination), first cast both of them to `float` and then compare.

This matches some test cases from the official JSON Schema test suite.

Follow-up to [50010].

Props yakimun, stefanjoebstl, TimothyBlynJacobs, rachelbaker.
Fixes #52932.

git-svn-id: https://develop.svn.wordpress.org/trunk@50653 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Sergey Biryukov
2021-04-04 18:05:10 +00:00
parent 0f4d1d674c
commit 19ae5a9809
2 changed files with 23 additions and 0 deletions

View File

@ -1926,6 +1926,12 @@ function rest_are_values_equal( $value1, $value2 ) {
return true; return true;
} }
if ( is_int( $value1 ) && is_float( $value2 )
|| is_float( $value1 ) && is_int( $value2 )
) {
return (float) $value1 === (float) $value2;
}
return $value1 === $value2; return $value1 === $value2;
} }

View File

@ -250,6 +250,7 @@ class WP_Test_REST_Schema_Validation extends WP_UnitTestCase {
/** /**
* @ticket 51911 * @ticket 51911
* @ticket 52932
* *
* @dataProvider data_different_types_of_value_and_enum_elements * @dataProvider data_different_types_of_value_and_enum_elements
* *
@ -304,6 +305,14 @@ class WP_Test_REST_Schema_Validation extends WP_UnitTestCase {
), ),
true, true,
), ),
array(
1,
array(
'type' => 'integer',
'enum' => array( 0.0, 1.0 ),
),
true,
),
array( array(
1.0, 1.0,
array( array(
@ -378,6 +387,14 @@ class WP_Test_REST_Schema_Validation extends WP_UnitTestCase {
), ),
true, true,
), ),
array(
1,
array(
'type' => 'number',
'enum' => array( 0, 1 ),
),
true,
),
array( array(
1.0, 1.0,
array( array(