Implement basic router and a controller for simfile API. Need to make some changes...
[rock.divinelegy.git] / Services / Routing / Router.php
1 <?php
2
3 namespace Services\Routing;
4
5 use Services\Routing\Route;
6 use Services\Routing\IRouter;
7 use Services\Http\IHttpRequest;
8
9 class Router implements IRouter
10 {
11 private $_maps;
12 private $_routes = array();
13 private $_request;
14 private $_matchedRoute;
15
16 public function __construct($maps, IHttpRequest $request) {
17 $this->_request = $request;
18 $this->_maps = include $maps;
19
20 foreach($this->_maps as $pattern => $routeInfo)
21 {
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';
25
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);
28 }
29 }
30
31 public function getControllerName()
32 {
33 $matchedRoute = $this->findMatch();
34 return $matchedRoute ? $matchedRoute->getControllerName() : 'index';
35 }
36
37 public function getActionName()
38 {
39 $matchedRoute = $this->findMatch();
40 return $matchedRoute ? $matchedRoute->getActionName() : 'index';
41 }
42
43 private function findMatch()
44 {
45 if($this->_matchedRoute)
46 {
47 return $this->_matchedRoute;
48 }
49
50 foreach($this->_routes as $route)
51 {
52 if($route->matches($this->_request->getPath()) && $route->supports($this->_request->getMethod()))
53 {
54 $this->_matchedRoute = $route;
55 return $route;
56 }
57 }
58 }
59 }