Skip to content
This repository has been archived by the owner on Nov 2, 2018. It is now read-only.

Commit

Permalink
Added a new method to Zepto\Router to parse parameters from the URL
Browse files Browse the repository at this point in the history
  • Loading branch information
hassankhan committed Jan 29, 2014
1 parent 3e733e8 commit aebd11f
Showing 1 changed file with 34 additions and 6 deletions.
40 changes: 34 additions & 6 deletions library/Zepto/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ public function __construct(\Symfony\Component\HttpFoundation\Request $request)
}

/**
* Add HTTP GET routes
* Add HTTP GET route
*
* @see Zepto\Router::route()
* @param string $route
Expand All @@ -121,11 +121,10 @@ public function __construct(\Symfony\Component\HttpFoundation\Request $request)
public function get($route, \Closure $callback)
{
$this->route(new Route($route, $callback));
// return $this->route($route, $callback, 'GET');
}

/**
* Add HTTP POST routes
* Add HTTP POST route
*
* @see Zepto\Router::route()
* @param string $route
Expand Down Expand Up @@ -159,9 +158,9 @@ public function match($http_method = 'GET', $url)

/**
* Tries to match one of the URL routes to the current URL, otherwise
* execute the default function and return false.
* execute the not found handler
*
* @return array
* @return
*/
public function run()
{
Expand All @@ -170,15 +169,21 @@ public function run()
throw new \Exception('No routes exist in the routing table. Add some');
}

// Try and get a matching route for the current URL
$route = $this->match($this->request->getMethod(), $this->request->getPathInfo());

// Call not found handler if no match was found
if ($route === null) {
$this->not_found();
}
else {
// Set current route
$this->current_route = $route;
$params = array();

// Get parameters from request
$params = $this->parse_parameters($route);

// Execute callback
call_user_func_array($route->get_callback(), $params);
}
}
Expand Down Expand Up @@ -260,6 +265,29 @@ protected function route(Route $route, $http_method = 'GET')
return true;
}

/**
* Parses parameters from URI as per the given route's pattern
*
* @param Route $route
* @return array
*/
protected function parse_parameters(Route $route)
{
// Get all parameter matches from URL for this route
preg_match($route->get_pattern(), "{$this->request->getPathInfo()}/", $matches);

$params = array();

// Retrieve any matches
foreach ($matches as $key => $value) {
if (is_string($key)) {
$params[] = $value;
}
}

return $params;
}

protected function default_not_found_handler()
{
// Use Twig to do something nice
Expand Down

0 comments on commit aebd11f

Please sign in to comment.