diff --git a/src/wp-includes/rest-api/class-wp-rest-server.php b/src/wp-includes/rest-api/class-wp-rest-server.php index c7ffb5b7677d0..d4a6e17f74c3e 100644 --- a/src/wp-includes/rest-api/class-wp-rest-server.php +++ b/src/wp-includes/rest-api/class-wp-rest-server.php @@ -972,6 +972,20 @@ public function get_routes( $route_namespace = '' ) { */ $endpoints = apply_filters( 'rest_endpoints', $endpoints ); + if ( ! is_array( $endpoints ) ) { + _doing_it_wrong( + __METHOD__, + sprintf( + /* translators: %s: The name of the filter. */ + __( 'The %s filter must return an array of endpoints.' ), + 'rest_endpoints' + ), + '7.2.0' + ); + + $endpoints = array(); + } + // Normalize the endpoints. $defaults = array( 'methods' => '', diff --git a/tests/phpunit/tests/rest-api/rest-server.php b/tests/phpunit/tests/rest-api/rest-server.php index dce5a045f73db..fabe2972f183c 100644 --- a/tests/phpunit/tests/rest-api/rest-server.php +++ b/tests/phpunit/tests/rest-api/rest-server.php @@ -2082,6 +2082,44 @@ public function test_get_routes_no_namespace_overriding() { $this->assertSame( 204, $response->get_status(), '/test-ns/v1/test' ); } + /** + * @ticket 65953 + */ + public function test_get_routes_returns_array_when_rest_endpoints_filter_returns_null() { + $this->setExpectedIncorrectUsage( 'WP_REST_Server::get_routes' ); + + add_filter( 'rest_endpoints', '__return_null' ); + + $this->assertSame( array(), rest_get_server()->get_routes() ); + } + + /** + * @ticket 65953 + */ + public function test_dispatch_does_not_error_when_rest_endpoints_filter_returns_null() { + $this->setExpectedIncorrectUsage( 'WP_REST_Server::get_routes' ); + + register_rest_route( + 'test-ns/v1', + '/test', + array( + 'methods' => array( 'GET' ), + 'callback' => static function () { + return new WP_REST_Response( 'data', 204 ); + }, + 'permission_callback' => '__return_true', + ) + ); + + add_filter( 'rest_endpoints', '__return_null' ); + + $request = new WP_REST_Request( 'GET', '/test-ns/v1/test' ); + $response = rest_get_server()->dispatch( $request ); + + $this->assertSame( 404, $response->get_status() ); + $this->assertSame( 'rest_no_route', $response->as_error()->get_error_code() ); + } + /** * @ticket 50244 */