Make WordPress Core


Ignore:
Timestamp:
03/11/2025 02:17:41 PM (12 months ago)
Author:
TimothyBlynJacobs
Message:

REST API: Fix fatal error when making HEAD requests with _fields filter.

In [59889] the REST API controllers were adjusted to perform less work when responding to HEAD requests. The WP_REST_Response body would now be null, which caused issues with filters that expected the response body to be an array.

This commit sets the response body to be an empty array when preparing the response instead. The body will still be discarded, but this provides better backward comppatibility with code that assumes an array will be used.

See #56481.
Props antonvlasenko, timothyblynjacobs, mamaduka, wildworks.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/tests/phpunit/tests/rest-api/rest-comments-controller.php

    r59899 r59970  
    35683568            return null;
    35693569        }
    3570         $this->assertNull( $response->get_data(), 'The server should not generate a body in response to a HEAD request.' );
     3570        $this->assertSame( array(), $response->get_data(), 'The server should not generate a body in response to a HEAD request.' );
     3571    }
     3572
     3573    /**
     3574     * @dataProvider data_head_request_with_specified_fields_returns_success_response
     3575     * @ticket 56481
     3576     *
     3577     * @param string $path The path to test.
     3578     */
     3579    public function test_head_request_with_specified_fields_returns_success_response( $path ) {
     3580        $request = new WP_REST_Request( 'HEAD', sprintf( $path, self::$approved_id ) );
     3581        $request->set_param( '_fields', 'id' );
     3582        $server   = rest_get_server();
     3583        $response = $server->dispatch( $request );
     3584        add_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10, 3 );
     3585        $response = apply_filters( 'rest_post_dispatch', $response, $server, $request );
     3586        remove_filter( 'rest_post_dispatch', 'rest_filter_response_fields', 10 );
     3587
     3588        $this->assertSame( 200, $response->get_status(), 'The response status should be 200.' );
     3589    }
     3590
     3591    /**
     3592     * Data provider intended to provide paths for testing HEAD requests.
     3593     *
     3594     * @return array
     3595     */
     3596    public static function data_head_request_with_specified_fields_returns_success_response() {
     3597        return array(
     3598            'get_item request'  => array( '/wp/v2/comments/%d' ),
     3599            'get_items request' => array( '/wp/v2/comments' ),
     3600        );
    35713601    }
    35723602}
Note: See TracChangeset for help on using the changeset viewer.