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, jnylen0.
Merges [39594] to the 4.7 branch.
Fixes #39150.


git-svn-id: https://develop.svn.wordpress.org/branches/4.7@39609 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Dion Hulse 2016-12-16 05:42:23 +00:00
parent 4d3fb455f5
commit 321599cc46
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();
@ -414,6 +416,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',