class Router
{
/**
- * Array that holds all Route objects
+ * RouteCollection that holds all Route objects
*
- * @var array
+ * @var RouteCollection
*/
private $routes = array();
public function __construct(RouteCollection $collection)
{
$this->routes = $collection;
+
+ foreach ($this->routes->all() as $route) {
+ if (!is_null($route->getName())) {
+ $this->namedRoutes[$route->getName()] = $route;
+ }
+ }
}
/**
// strip GET variables from URL
if (($pos = strpos($requestUrl, '?')) !== false) {
- $requestUrl = substr($requestUrl, 0, $pos);
+ $requestUrl = substr($requestUrl, 0, $pos);
}
return $this->match($requestUrl, $requestMethod);
public function match($requestUrl, $requestMethod = 'GET')
{
foreach ($this->routes->all() as $routes) {
-
// compare server request method with route's allowed http methods
- if (! in_array($requestMethod, (array) $routes->getMethods())) {
+ if (!in_array($requestMethod, (array)$routes->getMethods())) {
continue;
}
$currentDir = dirname($_SERVER['SCRIPT_NAME']);
- $requestUrl = str_replace($currentDir, '', $requestUrl);
+ if ($currentDir != '/') {
+ $requestUrl = str_replace($currentDir, '', $requestUrl);
+ }
// check if request _url matches route regex. if not, return false.
- if (! preg_match("@^" . $this->basePath . $routes->getRegex() . "*$@i", $requestUrl, $matches)) {
+ if (!preg_match("@^" . $this->basePath . $routes->getRegex() . "*$@i", $requestUrl, $matches)) {
continue;
}
+ $matchedText = array_shift($matches);
$params = array();
if (preg_match_all("/:([\w-%]+)/", $routes->getUrl(), $argument_keys)) {
-
// grab array with matches
$argument_keys = $argument_keys[1];
+ // check arguments number
+ if(count($argument_keys) != count($matches)) {
+ continue;
+ }
+
// loop trough parameter names, store matching value in $params array
foreach ($argument_keys as $key => $name) {
if (isset($matches[$key + 1])) {
public function generate($routeName, array $params = array())
{
// Check if route exists
- if (! isset($this->namedRoutes[$routeName])) {
+ if (!isset($this->namedRoutes[$routeName])) {
throw new Exception("No route with the name $routeName has been found.");
}
foreach ($config['routes'] as $name => $route) {
$collection->attachRoute(new Route($route[0], array(
'_controller' => str_replace('.', '::', $route[1]),
- 'methods' => $route[2]
+ 'methods' => $route[2],
+ 'name' => $name
)));
}