<?php
class Router {
	var $path;
	var $routes = array();
	
	function __construct(&$locator) {
        $this->database =& $locator->get('database'); 
		
		if ((isset($_SERVER['PATH_INFO'])) && ($_SERVER['PATH_INFO'])) {
        	$path = urldecode($_SERVER['PATH_INFO']);
        } else {
	        $path = urldecode($_SERVER['REQUEST_URI']);
	        
			if (strpos($path, '.php') !== FALSE) {
				$base = $_SERVER['SCRIPT_NAME'];
	        } else {
	            $base = dirname($_SERVER['SCRIPT_NAME']);
	        }
			
	        if ($base != '/') {
	        	$length = strlen($base) + 1;
	        	$path   = substr($path, $length);
	        }
			
	        if (strstr($path, '?')) {
	            $path = substr($path, 0, strpos($path, '?'));
	        }
        }
			
		$sql  = "select * from url_alias where alias = '?'";
		$result = $this->database->getRow($this->database->parse($sql, trim($path, '/')));
			
		if ($result) {
			$this->path = $result['query'];
		} else {
			$this->path = trim($path, '/');
		}
	}
	
	function setRoutes($routes) {
		$this->routes = $routes;
	}
	
	function route(&$request) {
		if ($this->path) {
			$path = explode('/', $this->path);
			
			if (isset($this->routes[$path[0]])) {
				$route = explode('/', $this->routes[$path[0]]);
				
				$i = 0;
				
				while ($i < sizeof($path)) {
					if (isset($route[$i])) {
						$request->set($route[$i], $path[$i]);
					} else {
						$request->set($path[$i], isset($path[$i+1]) ? $path[$i+1] : NULL);
						
						$i++;
					}
					
					$i++;
				}
			}
		}
	}
}
?>