Skip to content
Permalink
Browse files

Add support for named route generation.

  • Loading branch information...
markstory committed May 9, 2012
1 parent f4483ed commit 40a81b5b7e6a95d000c92dd619cc38fef07b4d75
Showing with 45 additions and 4 deletions.
  1. +12 −2 lib/Cake/Routing/RouteCollection.php
  2. +15 −2 lib/Cake/Routing/Router.php
  3. +18 −0 lib/Cake/Test/TestCase/Routing/RouterTest.php
@@ -181,12 +181,22 @@ public function promote($which) {
}
/**
* Get a route out of the collection.
* Get route(s) out of the collection.
*
* @param int $index The index of the route you want.
* If a string argument is provided, the first matching
* route for the provided name will be returned.
*
* If an integer argument is provided, the route
* with that index will be returned.
*
* @param mixed $index The index or name of the route you want.
* @return mixed Either the route object or null.
*/
public function get($index) {
if (is_string($index)) {
$routes = isset($this->_routeTable[$index]) ? $this->_routeTable[$index] : array(null);
return $routes[0];
}
return isset($this->_routes[$index]) ? $this->_routes[$index] : null;
}
@@ -700,9 +700,22 @@ public static function url($url = null, $options = false) {
'plugin' => $params['plugin']
);
$output = self::$_routes->match($url, $params);
} elseif (is_string($url) && !$hasLeadingSlash && !$hasColonSlash) {
} elseif (
is_string($url) &&
!$hasLeadingSlash &&
!$hasColonSlash
) {
// named route.
$route = self::$_routes->get($url);
if (!$route) {
throw new Error\Exception(__d(
'cake_dev',
'No route matching the name "%s" was found.',
$url
));
}
$url = $options + $route->defaults + array('_name' => $url);
$output = self::$_routes->match($url, $params);
} else {
// String urls.
if (
@@ -797,6 +797,24 @@ public function testUrlGenerationNamedRoute() {
);
$url = Router::url('test', array('name' => 'mark'));
$this->assertEquals('/users/mark', $url);
$url = Router::url('test', array('name' => 'mark', 'page' => 1, 'sort' => 'title', 'dir' => 'desc'));
$this->assertEquals('/users/mark?page=1&sort=title&dir=desc', $url);
}
/**
* Test that using invalid names causes exceptions.
*
* @expectedException Cake\Error\Exception
* @return void
*/
public function testNamedRouteException() {
Router::connect(
'/users/:name',
array('controller' => 'users', 'action' => 'view'),
array('_name' => 'test')
);
$url = Router::url('junk', array('name' => 'mark'));
}
/**

0 comments on commit 40a81b5

Please sign in to comment.
You can’t perform that action at this time.