Skip to content

Commit b68e21a

Browse files
committed
Fix route matching with same pattern in collection
1 parent e6c2a46 commit b68e21a

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

src/RouteCollection.php

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,21 +104,23 @@ public function count(): int
104104
*/
105105
public function match(ServerRequestInterface $request, bool $checkAllowedMethods = true): ?Route
106106
{
107+
$routeWithNotAllowedMethod = null;
108+
107109
foreach ($this->routes as $route) {
108110
if (!$route->match($request)) {
109111
continue;
110112
}
111113

112-
if (!$checkAllowedMethods) {
114+
if ($route->isAllowedMethod($request->getMethod())) {
113115
return $route;
114116
}
115117

116-
if ($route->isAllowedMethod($request->getMethod())) {
117-
return $route;
118+
if ($routeWithNotAllowedMethod === null) {
119+
$routeWithNotAllowedMethod = $route;
118120
}
119121
}
120122

121-
return null;
123+
return $checkAllowedMethods ? null : $routeWithNotAllowedMethod;
122124
}
123125

124126
/**

tests/RouteCollectionTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,23 @@ public function testMatchWithoutCheckAllowedMethods(): void
189189
$this->assertNull($this->collection->match($request->withMethod('POST'), false));
190190
}
191191

192+
public function testMatchWithoutCheckAllowedMethodsForSamePatternAndNotSameMethod(): void
193+
{
194+
$handler = fn(): ResponseInterface => new Response();
195+
$get = new Route('get', '/test', $handler, ['GET']);
196+
$put = new Route('put', '/test', $handler, ['PUT']);
197+
198+
$this->collection->set($get);
199+
$this->collection->set($put);
200+
$request = (new ServerRequest())->withUri(new Uri('/test'));
201+
202+
$this->assertSame($get, $this->collection->match($request->withMethod('GET')));
203+
$this->assertSame($get, $this->collection->match($request->withMethod('GET'), false));
204+
205+
$this->assertSame($put, $this->collection->match($request->withMethod('PUT')));
206+
$this->assertSame($put, $this->collection->match($request->withMethod('PUT'), false));
207+
}
208+
192209
public function testUrlWithoutHost(): void
193210
{
194211
$this->collection->set($this->home);

0 commit comments

Comments
 (0)