Skip to content

Commit

Permalink
Account for HTTP method when matching routes.
Browse files Browse the repository at this point in the history
Prior to this change routes using more than one HTTP method could not
ever be matched with reverse routing.
  • Loading branch information
markstory committed Jul 14, 2014
1 parent 799da32 commit 0273d9f
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/Routing/Route/Route.php
Expand Up @@ -438,6 +438,12 @@ public function match(array $url, array $context = []) {
unset($url['_ext']);
}

// Check the method first as it is special.
if (!$this->_matchMethod($url)) {
return false;
}
unset($url['[method]'], $defaults['[method]']);

// Missing defaults is a fail.
if (array_diff_key($defaults, $url) !== []) {
return false;
Expand Down Expand Up @@ -500,6 +506,24 @@ public function match(array $url, array $context = []) {
return $this->_writeUrl($url, $pass, $query);
}

/**
* Check whether or not the URL's HTTP method matches.
*
* @param array $url The array for the URL being generated.
*/
protected function _matchMethod($url) {
if (empty($this->defaults['[method]'])) {
return true;
}
if (empty($url['[method]'])) {
return false;
}
if (!in_array(strtoupper($url['[method]']), (array)$this->defaults['[method]'])) {
return false;
}
return true;
}

/**
* Converts a matching route array into a URL string.
*
Expand Down
39 changes: 39 additions & 0 deletions tests/TestCase/Routing/Route/RouteTest.php
Expand Up @@ -680,6 +680,45 @@ public function testParseWithMultipleHttpMethodConditions() {
$this->assertEquals($expected, $route->parse('/sample'));
}

/**
* test that http header conditions can work with URL generation
*
* @return void
*/
public function testMatchWithMultipleHttpMethodConditions() {
$route = new Route('/sample', [
'controller' => 'posts',
'action' => 'index',
'[method]' => ['PUT', 'POST']
]);
$url = [
'controller' => 'posts',
'action' => 'index',
];
$this->assertFalse($route->match($url));

$url = [
'controller' => 'posts',
'action' => 'index',
'[method]' => 'GET',
];
$this->assertFalse($route->match($url));

$url = [
'controller' => 'posts',
'action' => 'index',
'[method]' => 'PUT',
];
$this->assertEquals('/sample', $route->match($url));

$url = [
'controller' => 'posts',
'action' => 'index',
'[method]' => 'POST',
];
$this->assertEquals('/sample', $route->match($url));
}

/**
* Test that the [type] condition works.
*
Expand Down

0 comments on commit 0273d9f

Please sign in to comment.