REST API: Fix warning when using set_param() on a JSON request with no body.

In [47559] the `WP_REST_Request::set_param()` method was adjusted to try and overwrite an existing parameter definition before forcing the value in the first parameter slot. If `set_param()` was called on a request with an `application/json` content type and an empty body, a PHP warning would be issued. This was due to the JSON parameter type not being set to an array when the body is empty.

This commit avoids the warning by adding an `is_array()` check before calling `array_key_exists`. Ideally, `WP_REST_Reuest::parse_json_params()` would set the JSON parameter type to an empty array in this case, but that is too large of a change at this point in the cycle.

Props manooweb.
Fixes #50786.


git-svn-id: https://develop.svn.wordpress.org/trunk@48642 602fd350-edb4-49c9-b593-d223f7449a82
This commit is contained in:
Timothy Jacobs 2020-07-27 18:44:14 +00:00
parent beba4bb73a
commit 5149a7efd5
2 changed files with 16 additions and 2 deletions

View File

@ -408,7 +408,7 @@ class WP_REST_Request implements ArrayAccess {
$order = $this->get_parameter_order();
foreach ( $order as $type ) {
if ( array_key_exists( $key, $this->params[ $type ] ) ) {
if ( is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
return true;
}
}
@ -433,7 +433,7 @@ class WP_REST_Request implements ArrayAccess {
$found_key = false;
foreach ( $order as $type ) {
if ( 'defaults' !== $type && array_key_exists( $key, $this->params[ $type ] ) ) {
if ( 'defaults' !== $type && is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
$this->params[ $type ][ $key ] = $value;
$found_key = true;
}

View File

@ -765,4 +765,18 @@ class Tests_REST_Request extends WP_UnitTestCase {
$this->assertEquals( array( 'param' => 'new_value' ), $request->get_json_params() );
$this->assertEquals( array( 'param' => 'new_value' ), $request->get_query_params() );
}
/**
* @ticket 50786
*/
public function test_set_param_with_invalid_json() {
$request = new WP_REST_Request();
$request->add_header( 'content-type', 'application/json' );
$request->set_method( 'POST' );
$request->set_body( '' );
$request->set_param( 'param', 'value' );
$this->assertTrue( $request->has_param( 'param' ) );
$this->assertEquals( 'value', $request->get_param( 'param' ) );
}
}