Skip to content

Commit

Permalink
Ensure current HTTP verb routes are matched prior to any * matched ro…
Browse files Browse the repository at this point in the history
…utes. Fixes #1240
  • Loading branch information
lonnieezell committed Oct 3, 2018
1 parent 55ae897 commit da43a39
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
19 changes: 18 additions & 1 deletion system/Router/RouteCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,9 @@ public function getRoutes($verb = null): array

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

foreach ($collection as $r)
{
Expand Down Expand Up @@ -558,6 +560,21 @@ public function getHTTPVerb(): string

//--------------------------------------------------------------------

/**
* Sets the current HTTP verb.
* Used primarily for testing.
*
* @param string $verb
*
* @return $this
*/
public function setHTTPVerb(string $verb)
{
$this->HTTPVerb = $verb;

return $this;
}

/**
* A shortcut method to add a number of routes at a single time.
* It does not allow any options to be set on the route, or to
Expand Down
31 changes: 31 additions & 0 deletions tests/system/Router/RouterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -270,4 +270,35 @@ public function testRouteWorksWithFilters()
}

//--------------------------------------------------------------------

/**
* @see https://github.com/bcit-ci/CodeIgniter4/issues/1240
*/
public function testMatchesCorrectlyWithMixedVerbs()
{
$this->collection->setHTTPVerb('get');

$this->collection->add('/', 'Home::index');
$this->collection->get('news', 'News::index');
$this->collection->get('news/(:segment)', 'News::view/$1');
$this->collection->add('(:any)', 'Pages::view/$1');

$router = new Router($this->collection);

$router->handle('/');
$this->assertEquals('\Home', $router->controllerName());
$this->assertEquals('index', $router->methodName());

$router->handle('news');
$this->assertEquals('\News', $router->controllerName());
$this->assertEquals('index', $router->methodName());

$router->handle('news/daily');
$this->assertEquals('\News', $router->controllerName());
$this->assertEquals('view', $router->methodName());

$router->handle('about');
$this->assertEquals('\Pages', $router->controllerName());
$this->assertEquals('view', $router->methodName());
}
}

0 comments on commit da43a39

Please sign in to comment.