Make WordPress Core


Ignore:
Timestamp:
05/02/2018 01:24:30 AM (7 years ago)
Author:
pento
Message:

REST API: Filter responses based on the _fields parameter, before data is processed.

Historically, the REST API would generate the entire response object, including running expensive filters, then it would apply the _fields parameter, discarding the fields that weren't specificed.

This change causes _fields to be applied earlier, so that only requested fields are processed.

Props danielbachhuber.
See #43874.

File:
1 edited

Legend:

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

    r42343 r43087  
    507507
    508508    /**
     509     * Gets an array of fields to be included on the response.
     510     *
     511     * Included fields are based on item schema and `_fields=` request argument.
     512     *
     513     * @since 4.9.6
     514     *
     515     * @param WP_REST_Request $request Full details about the request.
     516     * @return array Fields to be included in the response.
     517     */
     518    public function get_fields_for_response( $request ) {
     519        $schema = $this->get_item_schema();
     520        $fields = isset( $schema['properties'] ) ? array_keys( $schema['properties'] ) : array();
     521        if ( ! isset( $request['_fields'] ) ) {
     522            return $fields;
     523        }
     524        $requested_fields = is_array( $request['_fields'] ) ? $request['_fields'] : preg_split( '/[\s,]+/', $request['_fields'] );
     525        if ( 0 === count( $requested_fields ) ) {
     526            return $fields;
     527        }
     528        // Trim off outside whitespace from the comma delimited list.
     529        $requested_fields = array_map( 'trim', $requested_fields );
     530        // Always persist 'id', because it can be needed for add_additional_fields_to_object().
     531        if ( in_array( 'id', $fields, true ) ) {
     532            $requested_fields[] = 'id';
     533        }
     534        return array_intersect( $fields, $requested_fields );
     535    }
     536
     537    /**
    509538     * Retrieves an array of endpoint arguments from the item schema for the controller.
    510539     *
Note: See TracChangeset for help on using the changeset viewer.