diff --git a/src/App.php b/src/App.php index 703393d1..f858ec0d 100755 --- a/src/App.php +++ b/src/App.php @@ -502,6 +502,14 @@ public function match(Request $request, bool $fresh = false): ?Route foreach (self::$routes[$method] as $routeUrl => $route) { /** @var Route $route */ + if(str_ends_with($routeUrl, '/') && substr_count($routeUrl, '/') > 1) { + $routeUrl = rtrim($routeUrl, '/'); + } + + if(str_ends_with($url, '/') && substr_count($url, '/') > 1) { + $url = rtrim($url, '/'); + } + // convert urls like '/users/:uid/posts/:pid' to regular expression $regex = '@'.\preg_replace('@:[^/]+@', '([^/]+)', $routeUrl).'@'; diff --git a/tests/AppTest.php b/tests/AppTest.php index 8e325284..e2ee73c2 100755 --- a/tests/AppTest.php +++ b/tests/AppTest.php @@ -400,6 +400,9 @@ public function providerRouteMatching(): array return [ 'GET request' => [App::REQUEST_METHOD_GET, '/path1'], 'GET request on different route' => [App::REQUEST_METHOD_GET, '/path2'], + 'GET request with trailing slash #1' => [App::REQUEST_METHOD_GET, '/path3', '/path3/'], + 'GET request with trailing slash #2' => [App::REQUEST_METHOD_GET, '/path3/', '/path3/'], + 'GET request with trailing slash #3' => [App::REQUEST_METHOD_GET, '/path3/', '/path3'], 'POST request' => [App::REQUEST_METHOD_POST, '/path1'], 'PUT request' => [App::REQUEST_METHOD_PUT, '/path1'], 'PATCH request' => [App::REQUEST_METHOD_PATCH, '/path1'], @@ -415,9 +418,9 @@ public function providerRouteMatching(): array /** * @dataProvider providerRouteMatching */ - public function testCanMatchRoute(string $method, string $path, string $expected = null): void + public function testCanMatchRoute(string $method, string $path, string $url = null): void { - $expected ??= $path; + $url ??= $path; switch ($method) { case App::REQUEST_METHOD_GET: @@ -438,7 +441,7 @@ public function testCanMatchRoute(string $method, string $path, string $expected } $_SERVER['REQUEST_METHOD'] = $method; - $_SERVER['REQUEST_URI'] = $path; + $_SERVER['REQUEST_URI'] = $url; $this->assertEquals($expected, $this->app->match(new Request())); $this->assertEquals($expected, $this->app->getRoute());