1<?php
2
3namespace GO\Site\Components;
4
5
6class Router{
7
8	/**
9	 * @return StringHelper the route of the default controller, action or module. Defaults to 'sites/site'.
10	 */
11	public $defaultController = 'site/site';
12
13	/**
14	 *
15	 * @var Controller
16	 */
17	private $_controller;
18
19	/**
20	 * Creates a controller instance based on a route.
21	 * The route should contain the controller ID and the action ID.
22	 * It may also contain additional GET variables. All these must be concatenated together with slashes.
23	 *
24	 * @param StringHelper $route the route of the request.
25	 * @return array the controller instance and the action ID. Null if the controller class does not exist or the route is invalid.
26	 */
27	public function runController() {
28
29		$aroute = explode('/', $this->getRoute());
30		$module_id = $aroute[0];
31		if (!isset($aroute[1]) || !isset($aroute[2])){
32			$controller_id = 'front';
33			$action_id = 'content';
34			$module_id='site';
35		}else
36		{
37			$controller_id = $aroute[1];
38			$action_id = $aroute[2];
39		}
40
41		$className = 'GO\\' . ucfirst($module_id) . '\\Controller\\' . ucfirst($controller_id)."Controller"; //TODO: set $module
42		//$classFile = \GO::config()->root_path . 'modules/' . $module_id . '/controller' . DIRECTORY_SEPARATOR . ucfirst($controller_id) . 'Controller.php';
43
44		if (class_exists($className)) {
45			//if (is_subclass_of($className, 'GO\Site\Components\AbstractFrontController')) {
46
47			$action = $this->getControllerAction($action_id);
48			$controller = new $className;
49			$this->_controller = $controller;
50			$controller->run($action, $_REQUEST);
51
52		}else
53		{
54			header("HTTP/1.0 404 Not Found");
55      header("Status: 404 Not Found");
56
57			echo "404 not found (".$className.")";
58		}
59	}
60
61	public function getRoute() {
62		$route = \Site::urlManager()->parseUrl(\Site::request());
63
64		if (($route = trim($route, '/')) === '')
65			$route = $this->defaultController;
66		if (!\Site::urlManager()->caseSensitive)
67			$route = strtolower($route);
68		return $route;
69	}
70
71	public function getController() {
72		return $this->_controller;
73	}
74
75	/**
76	 * Parses a path info into an action ID and GET variables.
77	 * @param StringHelper $pathInfo path info
78	 * @return StringHelper action ID
79	 */
80	protected function getControllerAction($pathInfo) {
81		if (($pos = strpos($pathInfo, '/')) !== false) {
82			$manager = \Site::urlManager();
83			$manager->parsePathInfo((string) substr($pathInfo, $pos + 1));
84			$actionID = substr($pathInfo, 0, $pos);
85			return $manager->caseSensitive ? $actionID : strtolower($actionID);
86		}
87		else
88			return $pathInfo;
89	}
90}
91