[wp-trac] [WordPress Trac] #56804: More readable and faster check for array of arrays in register_rest_route()

WordPress Trac noreply at wordpress.org
Tue Oct 11 19:55:41 UTC 2022


#56804: More readable and faster check for array of arrays in register_rest_route()
-------------------------+--------------------
 Reporter:  TobiasBg     |      Owner:  (none)
     Type:  enhancement  |     Status:  new
 Priority:  normal       |  Milestone:  6.1.1
Component:  REST API     |    Version:  trunk
 Severity:  normal       |   Keywords:
  Focuses:  performance  |
-------------------------+--------------------
 In [54339] for #51986,
 {{{#!php
 <?php
 if ( count( array_filter( $arg_group['args'], 'is_array' ) ) !== count(
 $arg_group['args'] ) ) {
 }}}
 was used as a custom implementation of an `any()` function.

 This is not very readable and not that nice performance-wise
 (`array_filter()` will always loop the full array, even though we are only
 interested in finding one (the first) non-array).

 This should be simplified to a `foreach` loop that is left early once a
 match is found, for better readability and higher performance, e.g.:
 {{{#!php
 <?php
 foreach( $arg_group['args'] as $arg ) {
         if ( ! is_array( $arg ) ) {
                 _doing_it_wrong(
                         __FUNCTION__,
                         sprintf(
                                 /* translators: 1: $args, 2: The REST API
 route being registered. */
                                 __( 'REST API %1$s should be an array of
 arrays. Non-array value detected for %2$s.' ),
                                 '<code>$args</code>',
                                 '<code>' . $clean_namespace . '/' . trim(
 $route, '/' ) . '</code>'
                         ),
                         '6.1.0'
                 );
                 break; // Leave the foreach loop once one non-array
 argument was found.
         }
 }
 }}}

 (Follow-up to #51986 where this suggestion missed the deadline for
 6.1-RC1, taking into account the linked-to Slack discussion in that
 ticket, regarding the target milestone. The Version of this ticket should
 be 6.1, but that does not yet exist in Trac.)

-- 
Ticket URL: <https://core.trac.wordpress.org/ticket/56804>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list