[wp-trac] [WordPress Trac] #43874: REST API: Only render fields specific to request when _fields= is used
WordPress Trac
noreply at wordpress.org
Fri Apr 27 08:46:08 UTC 2018
#43874: REST API: Only render fields specific to request when _fields= is used
-----------------------------+------------------------------------
Reporter: danielbachhuber | Owner: (none)
Type: defect (bug) | Status: new
Priority: normal | Milestone: 4.9.6
Component: REST API | Version:
Severity: normal | Resolution:
Keywords: | Focuses: rest-api, performance
-----------------------------+------------------------------------
Comment (by schlessera):
Some thoughts on the approach in https://github.com/WordPress/wordpress-
develop/pull/12:
**Possible minor scalability optimization for current approach:**
If you `array_flip()` the array of fields at the start of the checks, you
can turn the individual checks from a linear array search (`O(n)`) into a
hash table lookup (`O(1)`). Probably not worth the hassle, as I doubt
we'll have field arrays with thousands of fields.
**Possible way to avoid code churn:**
Turn the `$fields = get_fields_for_response()` into a `$schema =
get_filtered_item_schema()`, so that all the checks remain unchanged.
**Possible way to make the code cleaner - variant A (with even more code
churn, though):**
Iterate over the `$fields` and use a `switch` statement:
{{{#!php
foreach( $this->get_fields_for_response( $request ) as $field ) {
switch ( $field ) {
case 'id':
$data['id'] = $user->ID;
break;
case 'username':
$data['username'] = $user->user_login;
break;
// [...]
}
}
}}}
**Possible way to make the code cleaner - variant B (with yet more code
churn):**
Iterate over the `$fields` and map them to methods:
{{{#!php
public function prepare_item_for_response( $user, $request ) {
// Could be deduced, but probably too much magic then.
$mapping = array(
'id' => 'get_id',
'username' => 'get_username'
);
foreach( $this->get_fields_for_response( $request ) as $field ) {
if ( ! array_key_exists( $field, $mapping ) {
// throw error
}
$method = $mapping[ $field ];
$data[ $field ] = $this->$method( $user, $request );
}
}
private function get_id( $user, $request ) {
return $user->ID;
}
private function get_username( $user, $request ) {
return $user->user_login;
}
// [...]
}}}
--
Ticket URL: <https://core.trac.wordpress.org/ticket/43874#comment:3>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform
More information about the wp-trac
mailing list