diff --git a/cake/libs/router.php b/cake/libs/router.php index 61b5b2a77..c3894ea36 100644 --- a/cake/libs/router.php +++ b/cake/libs/router.php @@ -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 * diff --git a/cake/tests/cases/libs/router.test.php b/cake/tests/cases/libs/router.test.php index d6a18a59c..02d590c3a 100644 --- a/cake/tests/cases/libs/router.test.php +++ b/cake/tests/cases/libs/router.test.php @@ -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'); + } } /**