Skip to content

Commit

Permalink
Merge pull request #96 from utopia-php/fix-route-mistmatch
Browse files Browse the repository at this point in the history
Fix route mismatch against shorter paths when params are missing
  • Loading branch information
eldadfux authored May 30, 2023
2 parents 19d3925 + e8e12a8 commit bc0144f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
5 changes: 5 additions & 0 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,11 @@ public function match(Request $request, bool $fresh = false): ?Route
continue;
}

// Check the paths have the same amount of segments
if (\substr_count($routeUrl, '/') !== \substr_count($url, '/')) {
continue;
}

\array_shift($this->matches);
$this->route = $route;

Expand Down
35 changes: 32 additions & 3 deletions tests/AppTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -404,10 +404,9 @@ public function providerRouteMatching(): array
'PUT request' => [App::REQUEST_METHOD_PUT, '/path1'],
'PATCH request' => [App::REQUEST_METHOD_PATCH, '/path1'],
'DELETE request' => [App::REQUEST_METHOD_DELETE, '/path1'],
// "/a/b/c" needs to be first
'3 separators' => [App::REQUEST_METHOD_GET, '/a/b/c'],
'1 separators' => [App::REQUEST_METHOD_GET, '/a/'],
'2 separators' => [App::REQUEST_METHOD_GET, '/a/b'],
'1 separators' => [App::REQUEST_METHOD_GET, '/a'],
'3 separators' => [App::REQUEST_METHOD_GET, '/a/b/c'],
];
}

Expand Down Expand Up @@ -443,6 +442,36 @@ public function testCanMatchRoute(string $method, string $path): void
$this->assertEquals($expected, $this->app->getRoute());
}

public function testNoMismatchRoute(): void
{
$requests = [
[
'path' => '/d/:id',
'url' => '/d/'
],
[
'path' => '/d/:id/e/:id2',
'url' => '/d/123/e/'
],
[
'path' => '/d/:id/e/:id2/f/:id3',
'url' => '/d/123/e/456/f/'
],
];

foreach ($requests as $request) {
App::get($request['path']);

$_SERVER['REQUEST_METHOD'] = App::REQUEST_METHOD_GET;
$_SERVER['REQUEST_URI'] = $request['url'];

$route = $this->app->match(new Request(), fresh: true);

$this->assertEquals(null, $route);
$this->assertEquals(null, $this->app->getRoute());
}
}

public function testCanMatchFreshRoute(): void
{
$route1 = App::get('/path1');
Expand Down

0 comments on commit bc0144f

Please sign in to comment.