REST API: Do not error on empty JSON body

It's fairly common for clients to send `Content-Type: application/json` with an
empty body.  While technically not valid JSON, we've historically supported
this behaviour, so it shouldn't cause an error.

Props JPry.
Fixes #39150.


git-svn-id: https://develop.svn.wordpress.org/trunk@39594 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
James Nylen 2016-12-13 03:33:14 +00:00
parent 012d1977e2
commit 68b6a6197b
2 changed files with 21 additions and 1 deletions

View File

@ -669,7 +669,12 @@ class WP_REST_Request implements ArrayAccess {
return true;
}
$params = json_decode( $this->get_body(), true );
$body = $this->get_body();
if ( empty( $body ) ) {
return true;
}
$params = json_decode( $body, true );
/*
* Check for a parsing error.

View File

@ -10,6 +10,8 @@
* @group restapi
*/
class Tests_REST_Request extends WP_UnitTestCase {
public $request;
public function setUp() {
parent::setUp();
@ -450,6 +452,19 @@ class Tests_REST_Request extends WP_UnitTestCase {
$this->assertEquals( JSON_ERROR_SYNTAX, $data['json_error_code'] );
}
public function test_has_valid_params_empty_json_no_error() {
if ( version_compare( PHP_VERSION, '5.3', '<' ) ) {
return $this->markTestSkipped( 'JSON validation is only available for PHP 5.3+' );
}
$this->request->set_header( 'Content-Type', 'application/json' );
$this->request->set_body( '' );
$valid = $this->request->has_valid_params();
$this->assertNotWPError( $valid );
}
public function test_has_multiple_invalid_params_validate_callback() {
$this->request->set_url_params( array(
'someinteger' => '123',