Skip to content

Commit

Permalink
Merge pull request #99 from utopia-php/fix-trailing-slash
Browse files Browse the repository at this point in the history
feat: add support for trailing slashes in routes and urls
  • Loading branch information
christyjacob4 authored Jun 3, 2023
2 parents a2fb128 + 0dfd196 commit 7a18a2b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
8 changes: 8 additions & 0 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -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).'@';

Expand Down
9 changes: 6 additions & 3 deletions tests/AppTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'],
Expand All @@ -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:
Expand All @@ -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());
Expand Down

0 comments on commit 7a18a2b

Please sign in to comment.