From 68b6a6197bb853895bc6ac184578bb3899045929 Mon Sep 17 00:00:00 2001 From: James Nylen Date: Tue, 13 Dec 2016 03:33:14 +0000 Subject: [PATCH] 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 --- .../rest-api/class-wp-rest-request.php | 7 ++++++- tests/phpunit/tests/rest-api/rest-request.php | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/wp-includes/rest-api/class-wp-rest-request.php b/src/wp-includes/rest-api/class-wp-rest-request.php index d37ab6175d..4dd0dc2090 100644 --- a/src/wp-includes/rest-api/class-wp-rest-request.php +++ b/src/wp-includes/rest-api/class-wp-rest-request.php @@ -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. diff --git a/tests/phpunit/tests/rest-api/rest-request.php b/tests/phpunit/tests/rest-api/rest-request.php index dd87e2b5c0..7953f65bad 100644 --- a/tests/phpunit/tests/rest-api/rest-request.php +++ b/tests/phpunit/tests/rest-api/rest-request.php @@ -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',