diff --git a/Slim/Routing/FastRouteDispatcher.php b/Slim/Routing/FastRouteDispatcher.php index 797746bbb..61abaeb2b 100644 --- a/Slim/Routing/FastRouteDispatcher.php +++ b/Slim/Routing/FastRouteDispatcher.php @@ -15,7 +15,12 @@ class FastRouteDispatcher extends GroupCountBased { /** - * @var string[][] + * @var string|null + */ + private ?string $allowedMethodsUri = null; + + /** + * @var string[] */ private array $allowedMethods = []; @@ -86,8 +91,8 @@ private function routingResults(string $httpMethod, string $uri): array */ public function getAllowedMethods(string $uri): array { - if (isset($this->allowedMethods[$uri])) { - return $this->allowedMethods[$uri]; + if ($this->allowedMethodsUri === $uri) { + return $this->allowedMethods; } $allowedMethods = []; @@ -104,6 +109,8 @@ public function getAllowedMethods(string $uri): array } } - return $this->allowedMethods[$uri] = array_keys($allowedMethods); + $this->allowedMethodsUri = $uri; + + return $this->allowedMethods = array_keys($allowedMethods); } } diff --git a/tests/Routing/FastRouteDispatcherTest.php b/tests/Routing/FastRouteDispatcherTest.php index 48e575ac4..11823aad0 100644 --- a/tests/Routing/FastRouteDispatcherTest.php +++ b/tests/Routing/FastRouteDispatcherTest.php @@ -107,6 +107,21 @@ public function testGetAllowedMethods($method, $uri, $callback, $allowedMethods) $this->assertSame($results, $allowedMethods); } + public function testGetAllowedMethodsReusesLastUriOnly() + { + /** @var FastRouteDispatcher $dispatcher */ + $dispatcher = simpleDispatcher(function (RouteCollector $r) { + $r->addRoute('GET', '/user', 'handler0'); + $r->addRoute('POST', '/post', 'handler1'); + }, $this->generateDispatcherOptions()); + + $this->assertSame(['GET'], $dispatcher->getAllowedMethods('/user')); + $this->assertSame(['POST'], $dispatcher->getAllowedMethods('/post')); + + // Repeating the first URI recomputes, as only the last result is kept. + $this->assertSame(['GET'], $dispatcher->getAllowedMethods('/user')); + } + public function testDuplicateVariableNameError() { $this->expectException(BadRouteException::class);