REST API: Support the JSON Schema pattern keyword.

Props jason_the_adams, birgire, sorenbronsted.
Fixes #44949.


git-svn-id: https://develop.svn.wordpress.org/trunk@47810 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Timothy Jacobs 2020-05-16 19:01:49 +00:00
parent 8b9823f536
commit d8a063eabb
2 changed files with 47 additions and 0 deletions

View File

@ -1382,6 +1382,14 @@ function rest_validate_value_from_schema( $value, $args, $param = '' ) {
)
);
}
if ( isset( $args['pattern'] ) ) {
$pattern = str_replace( '#', '\\#', $args['pattern'] );
if ( ! preg_match( '#' . $pattern . '#u', $value ) ) {
/* translators: 1: Parameter, 2: Pattern. */
return new WP_Error( 'rest_invalid_pattern', sprintf( __( '%1$s does not match pattern %2$s.' ), $param, $args['pattern'] ) );
}
}
}
if ( isset( $args['format'] ) ) {

View File

@ -727,4 +727,43 @@ class WP_Test_REST_Schema_Validation extends WP_UnitTestCase {
),
);
}
/**
* @ticket 44949
*/
public function test_string_pattern() {
$schema = array(
'type' => 'string',
'pattern' => '^a*$',
);
$this->assertTrue( rest_validate_value_from_schema( 'a', $schema ) );
$this->assertWPError( rest_validate_value_from_schema( 'b', $schema ) );
}
/**
* @ticket 44949
*/
public function test_string_pattern_with_escaped_delimiter() {
$schema = array(
'type' => 'string',
'pattern' => '#[0-9]+',
);
$this->assertTrue( rest_validate_value_from_schema( '#123', $schema ) );
$this->assertWPError( rest_validate_value_from_schema( '#abc', $schema ) );
}
/**
* @ticket 44949
*/
public function test_string_pattern_with_utf8() {
$schema = array(
'type' => 'string',
'pattern' => '^â{1}$',
);
$this->assertTrue( rest_validate_value_from_schema( 'â', $schema ) );
$this->assertWPError( rest_validate_value_from_schema( 'ââ', $schema ) );
}
}