Skip to content

Commit 4e18f78

Browse files
committed
REST API: Fix namespace shadowing issue in route matching logic.
Following [47260] a namespace such as "test-ns" prevents any namespace such as "test-ns/v1" from being found when matching routes. While not best practice, this was an unintentional back-compat break; this patch restores the original behavior. Props david.binda, TimothyBlynJacobs. Fixes #48530. git-svn-id: https://develop.svn.wordpress.org/trunk@47351 602fd350-edb4-49c9-b593-d223f7449a82
1 parent 74baee2 commit 4e18f78

2 files changed

Lines changed: 37 additions & 5 deletions

File tree

src/wp-includes/rest-api/class-wp-rest-server.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -879,16 +879,17 @@ public function dispatch( $request ) {
879879
$method = $request->get_method();
880880
$path = $request->get_route();
881881

882-
$routes = array();
882+
$with_namespace = array();
883883

884884
foreach ( $this->get_namespaces() as $namespace ) {
885-
if ( 0 === strpos( ltrim( $path, '/' ), $namespace ) ) {
886-
$routes = $this->get_routes( $namespace );
887-
break;
885+
if ( 0 === strpos( trailingslashit( ltrim( $path, '/' ) ), $namespace ) ) {
886+
$with_namespace[] = $this->get_routes( $namespace );
888887
}
889888
}
890889

891-
if ( ! $routes ) {
890+
if ( $with_namespace ) {
891+
$routes = array_merge( ...$with_namespace );
892+
} else {
892893
$routes = $this->get_routes();
893894
}
894895

tests/phpunit/tests/rest-api/rest-server.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1465,6 +1465,37 @@ public function test_get_routes_respects_namespace_parameter() {
14651465
}
14661466
}
14671467

1468+
/**
1469+
* @ticket 48530
1470+
*/
1471+
public function test_get_routes_no_namespace_overriding() {
1472+
register_rest_route(
1473+
'test-ns',
1474+
'/test',
1475+
array(
1476+
'methods' => array( 'GET' ),
1477+
'callback' => function() {
1478+
return new WP_REST_Response( 'data', 204 );
1479+
},
1480+
)
1481+
);
1482+
register_rest_route(
1483+
'test-ns/v1',
1484+
'/test',
1485+
array(
1486+
'methods' => array( 'GET' ),
1487+
'callback' => function() {
1488+
return new WP_REST_Response( 'data', 204 );
1489+
},
1490+
)
1491+
);
1492+
1493+
$request = new WP_REST_Request( 'GET', '/test-ns/v1/test' );
1494+
$response = rest_get_server()->dispatch( $request );
1495+
1496+
$this->assertEquals( 204, $response->get_status(), '/test-ns/v1/test' );
1497+
}
1498+
14681499
public function _validate_as_integer_123( $value, $request, $key ) {
14691500
if ( ! is_int( $value ) ) {
14701501
return new WP_Error( 'some-error', 'This is not valid!' );

0 commit comments

Comments
 (0)