WordPress.org

Make WordPress Core


Ignore:
Timestamp:
12/12/2018 08:50:22 PM (22 months ago)
Author:
desrosj
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, danielbachhuber.

Merges [43736] to trunk.

Fixes #45099.

Location:
trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • trunk

  • trunk/tests/phpunit/tests/rest-api/rest-controller.php

    r43571 r43986  
    232232        );
    233233    }
     234
     235    public function test_add_additional_fields_to_object_respects_fields_param() {
     236        $controller = new WP_REST_Test_Controller();
     237        $request    = new WP_REST_Request( 'GET', '/wp/v2/testroute' );
     238        $schema     = $controller->get_item_schema();
     239        $field      = 'somefield';
     240
     241        $listener = new MockAction();
     242        $method   = 'action';
     243
     244        register_rest_field(
     245            $schema['title'],
     246            $field,
     247            array(
     248                'get_callback' => array( $listener, $method ),
     249                'schema'       => array(
     250                    'type' => 'string',
     251                ),
     252            )
     253        );
     254
     255        $item = array();
     256
     257        $controller->prepare_item_for_response( $item, $request );
     258
     259        $first_call_count = $listener->get_call_count( $method );
     260
     261        $this->assertTrue( $first_call_count > 0 );
     262
     263        $request->set_param( '_fields', 'somestring' );
     264
     265        $controller->prepare_item_for_response( $item, $request );
     266
     267        $this->assertSame( $first_call_count, $listener->get_call_count( $method ) );
     268
     269        $request->set_param( '_fields', $field );
     270
     271        $controller->prepare_item_for_response( $item, $request );
     272
     273        $this->assertTrue( $listener->get_call_count( $method ) > $first_call_count );
     274    }
    234275}
Note: See TracChangeset for help on using the changeset viewer.