Make WordPress Core

Changeset 55361


Ignore:
Timestamp:
02/17/2023 03:43:47 PM (20 months ago)
Author:
TimothyBlynJacobs
Message:

REST API: Normalize WP_REST_Server::dispatch() to return a response object.

Previously, the rest_pre_dispatch filter could be used to return a WP_Error instance. This would cause a fatal error for rest_post_dispath
filters that were rightly expecting a WP_REST_Response object to be passed instead.

Props DaveFX, felipeelia.
Fixes #56566.

Location:
trunk
Files:
2 edited

Legend:

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

    r54965 r55361  
    985985
    986986        if ( ! empty( $result ) ) {
     987
     988            // Normalize to either WP_Error or WP_REST_Response...
     989            $result = rest_ensure_response( $result );
     990
     991            // ...then convert WP_Error across.
     992            if ( is_wp_error( $result ) ) {
     993                $result = $this->error_to_response( $result );
     994            }
     995
    987996            return $result;
    988997        }
  • trunk/tests/phpunit/tests/rest-api/rest-server.php

    r54915 r55361  
    923923            'untouched' => 'data',
    924924        );
    925         $result = rest_get_server()->embed_links( $data );
    926 
    927         $this->assertArrayNotHasKey( '_links', $data );
    928         $this->assertArrayNotHasKey( '_embedded', $data );
    929         $this->assertSame( 'data', $data['untouched'] );
     925        $result = rest_get_server()->embed_links( $data, true );
     926
     927        $this->assertArrayNotHasKey( '_links', $result );
     928        $this->assertArrayNotHasKey( '_embedded', $result );
     929        $this->assertSame( 'data', $result['untouched'] );
     930    }
     931
     932    /**
     933     * Ensure embed_links handles WP_Error objects returned by dispatch
     934     *
     935     * @ticket 56566
     936     */
     937    public function test_link_embedding_returning_wp_error() {
     938        $return_wp_error = function() {
     939            return new WP_Error( 'some-error', 'This is not valid!' );
     940        };
     941        add_filter( 'rest_pre_dispatch', $return_wp_error );
     942
     943        $mock = new MockAction();
     944        add_filter( 'rest_post_dispatch', array( $mock, 'filter' ) );
     945
     946        $response = new WP_REST_Response();
     947        $response->add_link( 'author', rest_url( 'test' ), array( 'embeddable' => true ) );
     948
     949        $data = rest_get_server()->response_to_data( $response, true );
     950
     951        $this->assertArrayHasKey( '_links', $data );
     952        $this->assertCount( 1, $mock->get_events() );
     953        $this->assertSame( 'some-error', $data['_embedded']['author'][0]['code'] );
    930954    }
    931955
Note: See TracChangeset for help on using the changeset viewer.