3 namespace Services\Routing
;
5 use Services\Routing\Route
;
6 use Services\Routing\IRouter
;
7 use Services\Http\IHttpRequest
;
9 class Router
implements IRouter
12 private $_routes = array();
14 private $_matchedRoute;
16 public function __construct($maps, IHttpRequest
$request) {
17 $this->_request
= $request;
18 $this->_maps
= include $maps;
20 foreach($this->_maps
as $pattern => $routeInfo)
22 $methods = isset($routeInfo['methods']) ?
$routeInfo['methods'] : array('GET');
23 $controller = isset($routeInfo['controller']) ?
$routeInfo['controller'] : 'index';
24 $action = isset($routeInfo['action']) ?
$routeInfo['action'] : 'index';
26 //TODO: really I should be using a builder or a factory with DI for this but yolo.
27 $this->_routes
[] = new Route($pattern, $methods, $controller, $action);
31 public function getControllerName()
33 $matchedRoute = $this->findMatch();
34 return $matchedRoute ?
$matchedRoute->getControllerName() : 'index';
37 public function getActionName()
39 $matchedRoute = $this->findMatch();
40 return $matchedRoute ?
$matchedRoute->getActionName() : 'index';
43 private function findMatch()
45 if($this->_matchedRoute
)
47 return $this->_matchedRoute
;
50 foreach($this->_routes
as $route)
52 if($route->matches($this->_request
->getPath()) && $route->supports($this->_request
->getMethod()))
54 $this->_matchedRoute
= $route;