Skip to content

Commit 5d9adba

Browse files
authored
Merge pull request #1285 from bcit-ci/routes
Ensure current HTTP verb routes are matched prior to any * matched ro…
2 parents ccd9267 + da43a39 commit 5d9adba

2 files changed

Lines changed: 49 additions & 1 deletion

File tree

system/Router/RouteCollection.php

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -518,7 +518,9 @@ public function getRoutes($verb = null): array
518518

519519
if (isset($this->routes[$verb]))
520520
{
521-
$collection = array_merge($this->routes['*'], $this->routes[$verb]);
521+
// Keep current verb's routes at the beginning so they're matched
522+
// before any of the generic, "add" routes.
523+
$collection = array_merge($this->routes[$verb], $this->routes['*']);
522524

523525
foreach ($collection as $r)
524526
{
@@ -558,6 +560,21 @@ public function getHTTPVerb(): string
558560

559561
//--------------------------------------------------------------------
560562

563+
/**
564+
* Sets the current HTTP verb.
565+
* Used primarily for testing.
566+
*
567+
* @param string $verb
568+
*
569+
* @return $this
570+
*/
571+
public function setHTTPVerb(string $verb)
572+
{
573+
$this->HTTPVerb = $verb;
574+
575+
return $this;
576+
}
577+
561578
/**
562579
* A shortcut method to add a number of routes at a single time.
563580
* It does not allow any options to be set on the route, or to

tests/system/Router/RouterTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,4 +270,35 @@ public function testRouteWorksWithFilters()
270270
}
271271

272272
//--------------------------------------------------------------------
273+
274+
/**
275+
* @see https://github.com/bcit-ci/CodeIgniter4/issues/1240
276+
*/
277+
public function testMatchesCorrectlyWithMixedVerbs()
278+
{
279+
$this->collection->setHTTPVerb('get');
280+
281+
$this->collection->add('/', 'Home::index');
282+
$this->collection->get('news', 'News::index');
283+
$this->collection->get('news/(:segment)', 'News::view/$1');
284+
$this->collection->add('(:any)', 'Pages::view/$1');
285+
286+
$router = new Router($this->collection);
287+
288+
$router->handle('/');
289+
$this->assertEquals('\Home', $router->controllerName());
290+
$this->assertEquals('index', $router->methodName());
291+
292+
$router->handle('news');
293+
$this->assertEquals('\News', $router->controllerName());
294+
$this->assertEquals('index', $router->methodName());
295+
296+
$router->handle('news/daily');
297+
$this->assertEquals('\News', $router->controllerName());
298+
$this->assertEquals('view', $router->methodName());
299+
300+
$router->handle('about');
301+
$this->assertEquals('\Pages', $router->controllerName());
302+
$this->assertEquals('view', $router->methodName());
303+
}
273304
}

0 commit comments

Comments
 (0)