WordPress.org

Make WordPress Core

Changeset 47843


Ignore:
Timestamp:
05/22/2020 08:58:50 PM (4 months ago)
Author:
whyisjake
Message:

REST API: Ensure proper namespacing when registering routes.
The PR will corerce routes that have a leading slash and throwing a _doing_it_wrong notice while ensuring a proper namespace.

This brings the changes from [47842] to the 5.4 branch.

Fixes #49749.
Props TimothyBlynJacobs, skarabeq, afercia, skithund.

Location:
branches/5.4
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • branches/5.4

  • branches/5.4/src/wp-includes/rest-api.php

    r47362 r47843  
    4545    }
    4646
     47    $clean_namespace = trim( $namespace, '/' );
     48
     49    if ( $clean_namespace !== $namespace ) {
     50        _doing_it_wrong( __FUNCTION__, __( 'Namespace must not start or end with a slash.' ), '5.4.2' );
     51    }
     52
    4753    if ( ! did_action( 'rest_api_init' ) ) {
    4854        _doing_it_wrong(
     
    8591    }
    8692
    87     $full_route = '/' . trim( $namespace, '/' ) . '/' . trim( $route, '/' );
    88     rest_get_server()->register_route( $namespace, $full_route, $args, $override );
     93    $full_route = '/' . $clean_namespace . '/' . trim( $route, '/' );
     94    rest_get_server()->register_route( $clean_namespace, $full_route, $args, $override );
    8995    return true;
    9096}
  • branches/5.4/tests/phpunit/tests/rest-api.php

    r47563 r47843  
    955955    public function test_rest_parse_embed_param( $expected, $embed ) {
    956956        $this->assertEquals( $expected, rest_parse_embed_param( $embed ) );
     957    }
     958
     959    /**
     960     * @ticket 49749
     961     */
     962    public function test_register_route_with_invalid_namespace() {
     963        $this->setExpectedIncorrectUsage( 'register_rest_route' );
     964
     965        register_rest_route(
     966            '/my-namespace/v1/',
     967            '/my-route',
     968            array(
     969                'callback' => '__return_true',
     970            )
     971        );
     972
     973        $routes = rest_get_server()->get_routes( 'my-namespace/v1' );
     974        $this->assertCount( 2, $routes );
     975
     976        $this->assertTrue( rest_do_request( '/my-namespace/v1/my-route' )->get_data() );
    957977    }
    958978
Note: See TracChangeset for help on using the changeset viewer.