Skip to content

Commit 506682f

Browse files
committed
Match route with or without trailing slash
1 parent ff8c44f commit 506682f

File tree

2 files changed

+34
-3
lines changed

2 files changed

+34
-3
lines changed

src/Router.php

+22-3
Original file line numberDiff line numberDiff line change
@@ -568,14 +568,33 @@ protected function makeMatchedRoute() : Route
568568
$method = 'GET';
569569
}
570570
$url = $this->response->getRequest()->getUrl();
571-
$this->setMatchedPath($url->getPath());
571+
$path = $this->makePath($url->getPath());
572+
$this->setMatchedPath($path);
572573
$this->setMatchedOrigin($url->getOrigin());
573574
$this->matchedCollection = $this->matchCollection($url->getOrigin());
574575
if ( ! $this->matchedCollection) {
575576
return $this->matchedRoute = $this->getDefaultRouteNotFound();
576577
}
577-
return $this->matchedRoute = $this->matchRoute($method, $this->matchedCollection, $url->getPath())
578-
?? $this->getAlternativeRoute($method, $this->matchedCollection);
578+
return $this->matchedRoute = $this->matchRoute(
579+
$method,
580+
$this->matchedCollection,
581+
$path
582+
) ?? $this->getAlternativeRoute($method, $this->matchedCollection);
583+
}
584+
585+
/**
586+
* Creates a path without a trailing slash to be able to match both with and
587+
* without a slash at the end.
588+
*
589+
* @since 3.4.3
590+
*
591+
* @param string $path
592+
*
593+
* @return string
594+
*/
595+
protected function makePath(string $path) : string
596+
{
597+
return '/' . \trim($path, '/');
579598
}
580599

581600
protected function getAlternativeRoute(string $method, RouteCollection $collection) : Route

tests/RouterTest.php

+12
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,18 @@ public function testMatchRoute() : void
179179
self::assertInstanceOf(RouteCollection::class, $this->router->getMatchedCollection());
180180
}
181181

182+
public function testMatchRouteWithTrailingSlash() : void
183+
{
184+
$this->prepare([
185+
'REQUEST_METHOD' => 'PATCH',
186+
'REQUEST_URI' => '/post/25/',
187+
]);
188+
$this->router->match();
189+
self::assertSame('post.update', $this->router->getMatchedRoute()->getName());
190+
self::assertSame(['25'], $this->router->getMatchedRoute()->getActionArguments());
191+
self::assertInstanceOf(RouteCollection::class, $this->router->getMatchedCollection());
192+
}
193+
182194
public function testGetMatchedUrl() : void
183195
{
184196
self::assertNull($this->router->getMatchedUrl());

0 commit comments

Comments
 (0)