Skip to content

Commit

Permalink
Adding Router::reverse and basic test case.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Dec 28, 2009
1 parent 1eff024 commit 886cd9e
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
21 changes: 21 additions & 0 deletions cake/libs/router.php
Expand Up @@ -981,6 +981,27 @@ function queryString($q, $extra = array(), $escape = false) {
return $out;
}

/**
* Reverses a parsed parameter array into a string. Works similarily to Router::url(), but
* Since parsed URL's contain additional 'pass' and 'named' as well as 'url.url' keys.
* Those keys need to be specially handled in order to reverse a params array into a string url.
*
* @param array $param The params array that needs to be reversed.
* @return string The string that is the reversed result of the array
* @access public
*/
function reverse($params) {
$pass = $params['pass'];
$named = $params['named'];
$url = $params['url'];
unset($params['pass'], $params['named'], $params['url'], $url['url']);
$params = array_merge($params, $pass, $named);
if (!empty($url)) {
$params['q'] = $url;
}
return Router::url($params);
}

/**
* Normalizes a URL for purposes of comparison
*
Expand Down
39 changes: 39 additions & 0 deletions cake/tests/cases/libs/router.test.php
Expand Up @@ -1942,6 +1942,45 @@ function testUsingCustomRouteClass() {
$result = Router::parse('/test');
$this->assertEqual($result, $expected);
}

/**
* test reversing parameter arrays back into strings.
*
* @return void
*/
function testRouterReverse() {
$params = array(
'controller' => 'posts',
'action' => 'view',
'pass' => array(1),
'named' => array(),
'url' => array()
);
$result = Router::reverse($params);
$this->assertEqual($result, '/posts/view/1');

$params = array(
'controller' => 'posts',
'action' => 'index',
'pass' => array(1),
'named' => array('page' => 1, 'sort' => 'Article.title', 'direction' => 'desc'),
'url' => array()
);
$result = Router::reverse($params);
$this->assertEqual($result, '/posts/index/1/page:1/sort:Article.title/direction:desc');

Router::connect('/:lang/:controller/:action/*', array(), array('lang' => '[a-z]{3}'));
$params = array(
'lang' => 'eng',
'controller' => 'posts',
'action' => 'view',
'pass' => array(1),
'named' => array(),
'url' => array('url' => 'eng/posts/view/1')
);
$result = Router::reverse($params);
$this->assertEqual($result, '/eng/posts/view/1');
}
}

/**
Expand Down

0 comments on commit 886cd9e

Please sign in to comment.