Router.php 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. <?php
  2. namespace Tools;
  3. /**
  4. * Will manager new connections to the server
  5. * and try to match the requests and the controllers
  6. **/
  7. class Router
  8. {
  9. /**
  10. * @var string $rootPath
  11. * Contains the application's root path (ex: http://myshop.com/) with trailing slash
  12. * Can be accessed read-only via $instance->rootPath
  13. **/
  14. private $rootPath;
  15. /**
  16. * @var string $rootPath
  17. * Contains the application's root path (ex: /srv/http/myshop/) with trailing slash
  18. * Can be accessed read-only via $instance->rootUrl
  19. **/
  20. private $rootUrl;
  21. /**
  22. * @var string $requestUrl
  23. * Contains request
  24. **/
  25. private $requestUrl;
  26. /**
  27. * @var array ( array ( uri => controller ) ) $routes
  28. **/
  29. private $routes;
  30. /**
  31. * @var \Tools\Context $context
  32. * /core/tools/Context.php
  33. * Contains website's informations
  34. **/
  35. private $context;
  36. /**
  37. * @var array RouteParams
  38. * Contains route parameter
  39. * ex: /product/:id will contains {
  40. * 0 => product
  41. * 1 => [ID]
  42. * ':id' => [ID]
  43. **/
  44. private $routeParams;
  45. /**
  46. * @var string $modulePath
  47. * Contains the module directory
  48. **/
  49. /**
  50. * @var string $moduleUrl
  51. * Contains the module Uri
  52. **/
  53. /**
  54. * @var string $themePath
  55. * Contains the theme directory
  56. **/
  57. /**
  58. * @var string $themeUrl
  59. * Contains the theme Uri
  60. **/
  61. /**
  62. * Create the router, initialize url and path
  63. **/
  64. public function __construct($server, $context)
  65. {
  66. $pos = strrpos($server["SCRIPT_NAME"], "/");
  67. $relativePath = (($pos === FALSE) ? "" : substr($server["SCRIPT_NAME"], 0, $pos));
  68. $this->rootPath = $server["DOCUMENT_ROOT"] . $relativePath . "/";
  69. $this->rootUrl = $server["REQUEST_SCHEME"] . "://" . $server["HTTP_HOST"] . $relativePath ."/";
  70. $this->requestUrl = substr($server["REQUEST_URI"], count($this->rootUrl) -1);
  71. $this->context = $context;
  72. $this->routes = array();
  73. }
  74. /**
  75. * Called after database initialization
  76. * Check the site url and redirect user if the HOST does not match
  77. * If the site url is not defined in database, do not redirect
  78. **/
  79. public function init($server)
  80. {
  81. $siteUrl = \Entity\Config::getConfig(null, "siteUrl");
  82. if ($siteUrl != $server["HTTP_HOST"] && $siteUrl !== null)
  83. {
  84. header("location: http://{$siteUrl}{$server['REQUEST_URI']}");
  85. die;
  86. }
  87. }
  88. /**
  89. * @return \Controller\AController controller
  90. * /core/controller/AController.php
  91. * Match request to a controller
  92. * return FALSE on failure (eg. 404)
  93. **/
  94. public function serveUrl()
  95. {
  96. //TODO trigger hook GET, POST
  97. $this->prepareUrl();
  98. $requestParams = explode("/", $this->requestUrl);
  99. foreach ($this->routes as $i)
  100. {
  101. $routeParams = explode("/", $i[0]);
  102. $p = $this->routeMatch($requestParams, $routeParams);
  103. if (!$p)
  104. continue;
  105. $controller = $this->createController($i[1], $p);
  106. if ($controller)
  107. return $controller;
  108. }
  109. return false;
  110. }
  111. /**
  112. * Create and return Controller for the given route
  113. * @param $className
  114. * @param array $routeParameters
  115. * @return \Tools\AController on succes, false otherwise
  116. **/
  117. private function createController($className, $params)
  118. {
  119. if (!class_exists($className))
  120. return false;
  121. try
  122. {
  123. $this->routeParams = $params;
  124. $result = new $className($this->context, $params);
  125. }
  126. catch (\Exception\Error404 $e)
  127. {
  128. return false;
  129. }
  130. if (!($result instanceof \Tools\AController))
  131. return false;
  132. return $result;
  133. }
  134. /**
  135. * Check if the request match route
  136. * @param array $request User request
  137. * @param array $route Route to check
  138. * @return array on success, false on failure
  139. **/
  140. private function routeMatch($request, $route)
  141. {
  142. $i = count($request);
  143. $params = array();
  144. if ($i != count($route))
  145. return false;
  146. while ($i)
  147. {
  148. $i--;
  149. if ($route[$i] == '' && $request[$i] == '')
  150. continue;
  151. if ($route[$i] == '' || $request[$i] == '')
  152. return false;
  153. if ($route[$i][0] != ':' && ($route[$i] != $request[$i]))
  154. return false;
  155. if ($route[$i][0] == ':')
  156. $params[$route[$i]] = $request[$i];
  157. $params[$i -1] = $request[$i];
  158. }
  159. return array_reverse($params);
  160. }
  161. /**
  162. * Append local routes to router
  163. * Will load CMS pages, categories page, products page, cart pages, etc.
  164. **/
  165. private function prepareUrl()
  166. {
  167. $fetcher = new \Entity\Cms();
  168. $pages = $fetcher->selects(null, array("order"));
  169. foreach ($pages as $i)
  170. $this->doRouteAdd($i->shurl, $i->controller);
  171. }
  172. /**
  173. * Add a route to the internal route list
  174. * Internal procedure
  175. **/
  176. private function doRouteAdd($route, $controller)
  177. {
  178. $this->routes[] = array($route, $controller);
  179. }
  180. /**
  181. * @param string $route Uri to match the controller
  182. * Uri can be formatted as '/:param/static'.
  183. * expl. '/product/:id/'
  184. * @param string $controller Controller class name.
  185. * new $controller() MUST return a \Tool\AController instance
  186. *
  187. * Add a route and a Controller to the list
  188. * Can only be called from `routerSetup' hook
  189. **/
  190. public function routeAdd($route, $controller)
  191. {
  192. if (!$this->context->hookManager->isInHook("routerSetup"))
  193. throw new \Exception("You can only add routes from `routerSetup' hook");
  194. $this->doRouteAdd($route, $controller);
  195. }
  196. /**
  197. * Getter
  198. **/
  199. public function __get($key)
  200. {
  201. switch ($key)
  202. {
  203. case "rootPath": return $this->rootPath; break;
  204. case "rootUrl": return $this->rootUrl; break;
  205. case "modulesPath": return $this->rootPath."content/modules/"; break;
  206. case "modulesUrl": return $this->rootUrl."content/modules/"; break;
  207. case "themesPath": return $this->rootPath."content/theme/"; break;
  208. case "themesUrl": return $this->rootUrl."content/theme/"; break;
  209. }
  210. throw new \Exception("Cannot access attribute {$key}");
  211. }
  212. }