[wp-trac] [WordPress Trac] #55292: Custom REST Endpoints without Regex

WordPress Trac noreply at wordpress.org
Wed Mar 2 08:39:53 UTC 2022


#55292: Custom REST Endpoints without Regex
-------------------------------------+-----------------------------
 Reporter:  encoredev                |      Owner:  (none)
     Type:  feature request          |     Status:  assigned
 Priority:  normal                   |  Milestone:  Awaiting Review
Component:  REST API                 |    Version:  5.9.1
 Severity:  normal                   |   Keywords:  2nd-opinion
  Focuses:  accessibility, rest-api  |
-------------------------------------+-----------------------------
 The current way of defining the path for the REST endpoints requires regex
 expressions to define the route variables. That feels like a very
 convoluted way for such a simple and a common task.
 Here is the example from the docs:
 {{{
 /author/(?P<id>\d+)
 }}}
 What I am suggesting is to allow a second way of defining the path which
 will look like that:
 {{{
 /author/{id}
 }}}
 Then this can be parsed and all of the sections in curly braces can be
 replaced with regex expressions matching a string value like that:
 {{{
 /author/(?P<id>\S+).
 }}}
 Which worked fine even with more complicated examples like:
 {{{
 "/author/{category}/{subcategory}/{id}" turns into
 "/author/(?P<category>\S+)/(?P<subcategory>\S+)/(?P<id>\S+)"
 }}}

 And here is the implementation of the parsing function:
 {{{#!php
 <?php
         protected function path_add_regex( string $path ): string {
                 $path_elements = preg_split( '/({[^}]*})/', $path, 0,
 PREG_SPLIT_DELIM_CAPTURE );
                 foreach ( $path_elements as &$element ) {
                         if ( str_contains( $element, '{' ) &&
 str_contains( $element, '}' ) ) {
                                 $element = str_replace( '{', '', $element
 );
                                 $element = str_replace( '}', '', $element
 );
                                 $element = "(?P<{$element}>\S+)";
                         }
                 }
                 $path = implode( '', $path_elements );
                 return $path;
         }
 }}}

 So far I have got around 40 routes defined in the suggested way. They are
 of various complexity and I have never needed to use regex for any of
 them.

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


More information about the wp-trac mailing list