WordPress.org

Make WordPress Core


Ignore:
Timestamp:
10/17/2018 02:40:23 AM (3 years ago)
Author:
danielbachhuber
Message:

REST API: Don't add fields to object when not included in ?_fields=.

In [43087], we improved REST API performance by only rendering the fields specified in the request. Similarly, any fields registered with register_rest_field() should only be rendered when included in ?_fields=.

Props dlh.
Fixes #45099.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/5.0/tests/phpunit/tests/rest-api/rest-controller.php

    r43445 r43736  
    214214        ), $fields );
    215215    }
     216
     217    public function test_add_additional_fields_to_object_respects_fields_param() {
     218        $controller = new WP_REST_Test_Controller();
     219        $request    = new WP_REST_Request( 'GET', '/wp/v2/testroute' );
     220        $schema     = $controller->get_item_schema();
     221        $field      = 'somefield';
     222
     223        $listener = new MockAction();
     224        $method = 'action';
     225
     226        register_rest_field(
     227            $schema['title'],
     228            $field,
     229            array(
     230                'get_callback' => array( $listener, $method ),
     231                'schema'       => array(
     232                    'type' => 'string',
     233                ),
     234            )
     235        );
     236
     237        $item = array();
     238
     239        $controller->prepare_item_for_response( $item, $request );
     240
     241        $first_call_count = $listener->get_call_count( $method );
     242
     243        $this->assertTrue( $first_call_count > 0 );
     244
     245        $request->set_param( '_fields', 'somestring' );
     246
     247        $controller->prepare_item_for_response( $item, $request );
     248
     249        $this->assertSame( $first_call_count, $listener->get_call_count( $method ) );
     250
     251        $request->set_param( '_fields', $field );
     252
     253        $controller->prepare_item_for_response( $item, $request );
     254
     255        $this->assertTrue( $listener->get_call_count( $method ) > $first_call_count );
     256    }
    216257}
Note: See TracChangeset for help on using the changeset viewer.