REST API: Improve formatting of failed validation errors.

If a validation_callback returns a WP_Error it should give the same response format as if it returned `false`. This makes programmatically reading the validation errors better.

Props bradyvercher for initial patch.
Fixes #35028.


git-svn-id: https://develop.svn.wordpress.org/trunk@35890 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Joe Hoyle 2015-12-12 18:22:02 +00:00
parent cca457a958
commit a375d93001
3 changed files with 32 additions and 3 deletions

2
.gitignore vendored
View File

@ -1,5 +1,5 @@
# gitignore file for WordPress Core
.svn
# Configuration files with possibly sensitive information
wp-config.php
wp-tests-config.php

View File

@ -851,13 +851,13 @@ class WP_REST_Request implements ArrayAccess {
}
if ( is_wp_error( $valid_check ) ) {
$invalid_params[] = sprintf( '%s (%s)', $key, $valid_check->get_error_message() );
$invalid_params[ $key ] = $valid_check->get_error_message();
}
}
}
if ( $invalid_params ) {
return new WP_Error( 'rest_invalid_param', sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', $invalid_params ) ), array( 'status' => 400, 'params' => $invalid_params ) );
return new WP_Error( 'rest_invalid_param', sprintf( __( 'Invalid parameter(s): %s' ), implode( ', ', array_keys( $invalid_params ) ) ), array( 'status' => 400, 'params' => $invalid_params ) );
}
return true;

View File

@ -391,4 +391,33 @@ class Tests_REST_Request extends WP_UnitTestCase {
$this->assertArrayHasKey( 'someinteger', $data['params'] );
$this->assertArrayHasKey( 'someotherinteger', $data['params'] );
}
public function test_invalid_params_error_response_format() {
$this->request->set_url_params( array(
'someinteger' => '123',
'someotherparams' => '123',
));
$this->request->set_attributes( array(
'args' => array(
'someinteger' => array(
'validate_callback' => '__return_false',
),
'someotherparams' => array(
'validate_callback' => array( $this, '_return_wp_error_on_validate_callback' ),
),
),
));
$valid = $this->request->has_valid_params();
$this->assertWPError( $valid );
$error_data = $valid->get_error_data();
$this->assertEquals( array( 'someinteger', 'someotherparams' ), array_keys( $error_data['params'] ) );
$this->assertEquals( 'This is not valid!', $error_data['params']['someotherparams'] );
}
public function _return_wp_error_on_validate_callback() {
return new WP_Error( 'some-error', 'This is not valid!' );
}
}