diff --git a/src/wp-includes/rest-api.php b/src/wp-includes/rest-api.php index 5d8d34cd6b..8ad3cbc14a 100644 --- a/src/wp-includes/rest-api.php +++ b/src/wp-includes/rest-api.php @@ -1315,7 +1315,7 @@ function rest_is_boolean( $maybe_bool ) { * @return bool True if an integer, otherwise false. */ function rest_is_integer( $maybe_integer ) { - return round( floatval( $maybe_integer ) ) === floatval( $maybe_integer ); + return is_numeric( $maybe_integer ) && round( floatval( $maybe_integer ) ) === floatval( $maybe_integer ); } /** diff --git a/tests/phpunit/tests/rest-api.php b/tests/phpunit/tests/rest-api.php index e9d9b50c5d..3a1240827b 100644 --- a/tests/phpunit/tests/rest-api.php +++ b/tests/phpunit/tests/rest-api.php @@ -1918,6 +1918,69 @@ class Tests_REST_API extends WP_UnitTestCase { ); } + /** + * @ticket 51146 + * + * @dataProvider _dp_rest_is_integer + * + * @param bool $expected Expected result of the check. + * @param mixed $value The value to check. + */ + public function test_rest_is_integer( $expected, $value ) { + $is_integer = rest_is_integer( $value ); + + if ( $expected ) { + $this->assertTrue( $is_integer ); + } else { + $this->assertFalse( $is_integer ); + } + } + + public function _dp_rest_is_integer() { + return array( + array( + true, + 1, + ), + array( + true, + '1', + ), + array( + true, + 0, + ), + array( + true, + -1, + ), + array( + true, + '05', + ), + array( + false, + 'garbage', + ), + array( + false, + 5.5, + ), + array( + false, + '5.5', + ), + array( + false, + array(), + ), + array( + false, + true, + ), + ); + } + /** * @ticket 50300 * @@ -2018,6 +2081,11 @@ class Tests_REST_API extends WP_UnitTestCase { 'a,b', array( 'array', 'string' ), ), + array( + 'string', + 'hello', + array( 'integer', 'string' ), + ), ); } } diff --git a/tests/phpunit/tests/rest-api/rest-schema-validation.php b/tests/phpunit/tests/rest-api/rest-schema-validation.php index b31b86bb19..d6d94ae686 100644 --- a/tests/phpunit/tests/rest-api/rest-schema-validation.php +++ b/tests/phpunit/tests/rest-api/rest-schema-validation.php @@ -1040,4 +1040,20 @@ class WP_Test_REST_Schema_Validation extends WP_UnitTestCase { $data[1] = array_reverse( $data[1] ); $this->assertTrue( rest_validate_value_from_schema( $data, $schema ) ); } + + /** + * @ticket 50300 + */ + public function test_string_or_integer() { + $schema = array( + 'type' => array( 'integer', 'string' ), + ); + + $this->assertTrue( rest_validate_value_from_schema( 'garbage', $schema ) ); + $this->assertTrue( rest_validate_value_from_schema( 15, $schema ) ); + $this->assertTrue( rest_validate_value_from_schema( '15', $schema ) ); + $this->assertTrue( rest_validate_value_from_schema( '15.5', $schema ) ); + $this->assertWPError( rest_validate_value_from_schema( 15.5, $schema ) ); + } + }