Adding Router::reverse and basic test case.

This commit is contained in:
Mark Story 2009-12-27 23:09:26 -05:00
parent 1eff024e7e
commit 886cd9e719
2 changed files with 60 additions and 0 deletions

View file

@ -981,6 +981,27 @@ class Router {
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
*

View file

@ -1942,6 +1942,45 @@ class RouterTest extends CakeTestCase {
$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');
}
}
/**