From 886cd9e719beae718b4f6aadbcb0f7ffc5eec367 Mon Sep 17 00:00:00 2001 From: Mark Story Date: Sun, 27 Dec 2009 23:09:26 -0500 Subject: [PATCH] Adding Router::reverse and basic test case. --- cake/libs/router.php | 21 +++++++++++++++ cake/tests/cases/libs/router.test.php | 39 +++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) diff --git a/cake/libs/router.php b/cake/libs/router.php index 61b5b2a779b..c3894ea3658 100644 --- a/cake/libs/router.php +++ b/cake/libs/router.php @@ -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 * diff --git a/cake/tests/cases/libs/router.test.php b/cake/tests/cases/libs/router.test.php index d6a18a59c4d..02d590c3af6 100644 --- a/cake/tests/cases/libs/router.test.php +++ b/cake/tests/cases/libs/router.test.php @@ -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'); + } } /**