WordPress.org

Make WordPress Core


Ignore:
Timestamp:
02/11/2020 03:20:05 AM (10 months ago)
Author:
kadamwhite
Message:

REST API: Match REST API routes on namespace before performing regex checks.

Rule out groups of API endpoints by simple namespace string comparison to reduce the number of regex checks necessary when matching a route.

Props TimothyBlynJacobs.
Fixes #48530.

File:
1 edited

Legend:

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

    r47239 r47260  
    745745     *
    746746     * @since 4.4.0
    747      *
     747     * @since 5.4.0 Add $namespace parameter.
     748     *
     749     * @param string $namespace Optionally, only return routes in the given namespace.
    748750     * @return array `'/path/regex' => array( $callback, $bitmask )` or
    749751     *               `'/path/regex' => array( array( $callback, $bitmask ), ...)`.
    750752     */
    751     public function get_routes() {
     753    public function get_routes( $namespace = '' ) {
     754        $endpoints = $this->endpoints;
     755
     756        if ( $namespace ) {
     757            $endpoints = wp_list_filter( $endpoints, array( 'namespace' => $namespace ) );
     758        }
    752759
    753760        /**
     
    761768         *                         `'/path/regex' => array( array( $callback, $bitmask ).
    762769         */
    763         $endpoints = apply_filters( 'rest_endpoints', $this->endpoints );
     770        $endpoints = apply_filters( 'rest_endpoints', $endpoints );
    764771
    765772        // Normalise the endpoints.
     
    873880        $path   = $request->get_route();
    874881
    875         foreach ( $this->get_routes() as $route => $handlers ) {
     882        $routes = array();
     883
     884        foreach ( $this->get_namespaces() as $namespace ) {
     885            if ( 0 === strpos( ltrim( $path, '/' ), $namespace ) ) {
     886                $routes = $this->get_routes( $namespace );
     887                break;
     888            }
     889        }
     890
     891        if ( ! $routes ) {
     892            $routes = $this->get_routes();
     893        }
     894
     895        foreach ( $routes as $route => $handlers ) {
    876896            $match = preg_match( '@^' . $route . '$@i', $path, $matches );
    877897
Note: See TracChangeset for help on using the changeset viewer.