1
0
mirror of https://github.com/dannyvankooten/AltoRouter.git synced 2025-08-04 15:37:45 +02:00

Merge pull request #99 from koenpunt/bare-optional-parameter

Allow for optional parameters on bare/root url
This commit is contained in:
Koen Punt
2017-04-04 20:37:25 +02:00
committed by GitHub
2 changed files with 63 additions and 6 deletions

View File

@@ -139,7 +139,7 @@ class AltoRouter {
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
foreach($matches as $index => $match) {
list($block, $pre, $type, $param, $optional) = $match;
if ($pre) {
@@ -147,13 +147,17 @@ class AltoRouter {
}
if(isset($params[$param])) {
// Part is found, replace for param value
$url = str_replace($block, $params[$param], $url);
} elseif ($optional) {
} elseif ($optional && $index !== 0) {
// Only strip preceeding slash if it's not at the base
$url = str_replace($pre . $block, '', $url);
} else {
// Strip match block
$url = str_replace($block, '', $url);
}
}
}
return $url;
@@ -250,14 +254,18 @@ class AltoRouter {
$pre = '\.';
}
$optional = $optional !== '' ? '?' : null;
//Older versions of PCRE require the 'P' in (?P<named>)
$pattern = '(?:'
. ($pre !== '' ? $pre : null)
. '('
. ($param !== '' ? "?P<$param>" : null)
. $type
. '))'
. ($optional !== '' ? '?' : null);
. ')'
. $optional
. ')'
. $optional;
$route = str_replace($block, $pattern, $route);
}

View File

@@ -233,7 +233,27 @@ class AltoRouterTest extends PHPUnit_Framework_TestCase
$this->assertEquals('/test/someaction.json',
$this->router->generate('bar_route', $params));
}
/**
* GitHub #98
*/
public function testGenerateWithOptionalPartOnBareUrl()
{
$this->router->map('GET', '/[i:page]?', function(){}, 'bare_route');
$params = array(
'page' => 1
);
$this->assertEquals('/1',
$this->router->generate('bare_route', $params));
$params = array();
$this->assertEquals('/',
$this->router->generate('bare_route', $params));
}
public function testGenerateWithNonexistingRoute()
{
try{
@@ -364,6 +384,35 @@ class AltoRouterTest extends PHPUnit_Framework_TestCase
'name' => 'bar_route'
), $this->router->match('/bar/test/do.json', 'GET'));
$this->assertEquals(array(
'target' => 'bar_action',
'params' => array(
'controller' => 'test',
'action' => 'do'
),
'name' => 'bar_route'
), $this->router->match('/bar/test/do', 'GET'));
}
/**
* GitHub #98
*/
public function testMatchWithOptionalPartOnBareUrl(){
$this->router->map('GET', '/[i:page]?', 'bare_action', 'bare_route');
$this->assertEquals(array(
'target' => 'bare_action',
'params' => array(
'page' => 1
),
'name' => 'bare_route'
), $this->router->match('/1', 'GET'));
$this->assertEquals(array(
'target' => 'bare_action',
'params' => array(),
'name' => 'bare_route'
), $this->router->match('/', 'GET'));
}
public function testMatchWithWildcard()