Make WordPress Core

Changeset 48642


Ignore:
Timestamp:
07/27/2020 06:44:14 PM (4 years ago)
Author:
TimothyBlynJacobs
Message:

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.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/rest-api/class-wp-rest-request.php

    r48102 r48642  
    409409
    410410        foreach ( $order as $type ) {
    411             if ( array_key_exists( $key, $this->params[ $type ] ) ) {
     411            if ( is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
    412412                return true;
    413413            }
     
    434434
    435435        foreach ( $order as $type ) {
    436             if ( 'defaults' !== $type && array_key_exists( $key, $this->params[ $type ] ) ) {
     436            if ( 'defaults' !== $type && is_array( $this->params[ $type ] ) && array_key_exists( $key, $this->params[ $type ] ) ) {
    437437                $this->params[ $type ][ $key ] = $value;
    438438                $found_key                     = true;
  • trunk/tests/phpunit/tests/rest-api/rest-request.php

    r47559 r48642  
    766766        $this->assertEquals( array( 'param' => 'new_value' ), $request->get_query_params() );
    767767    }
     768
     769    /**
     770     * @ticket 50786
     771     */
     772    public function test_set_param_with_invalid_json() {
     773        $request = new WP_REST_Request();
     774        $request->add_header( 'content-type', 'application/json' );
     775        $request->set_method( 'POST' );
     776        $request->set_body( '' );
     777        $request->set_param( 'param', 'value' );
     778
     779        $this->assertTrue( $request->has_param( 'param' ) );
     780        $this->assertEquals( 'value', $request->get_param( 'param' ) );
     781    }
    768782}
Note: See TracChangeset for help on using the changeset viewer.