Router.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. // @codeCoverageIgnoreStart
  83. // This code is tested under another process
  84. if ($siteUrl != $server["HTTP_HOST"] && $siteUrl !== null)
  85. {
  86. header("location: http://{$siteUrl}{$server['REQUEST_URI']}");
  87. die;
  88. }
  89. // @codeCoverageIgnoreEnd
  90. }
  91. /**
  92. * @return \Controller\AController controller
  93. * /core/controller/AController.php
  94. * Match request to a controller
  95. * return FALSE on failure (eg. 404)
  96. **/
  97. public function serveUrl()
  98. {
  99. //TODO trigger hook GET, POST
  100. $this->prepareUrl();
  101. $requestParams = explode("/", $this->requestUrl);
  102. foreach ($this->routes as $i)
  103. {
  104. $routeParams = explode("/", $i[0]);
  105. $p = $this->routeMatch($requestParams, $routeParams);
  106. if ($p === false)
  107. continue;
  108. $controller = $this->createController($i[1], $p);
  109. if ($controller)
  110. return $controller;
  111. }
  112. return false;
  113. }
  114. /**
  115. * Create and return Controller for the given route
  116. * @param $className
  117. * @param array $routeParameters
  118. * @return \Tools\AController on succes, false otherwise
  119. **/
  120. private function createController($className, $params)
  121. {
  122. if (!class_exists($className))
  123. return false;
  124. $this->routeParams = $params;
  125. $result = null;
  126. try
  127. {
  128. $result = new $className($this->context, $params);
  129. if (!($result instanceof \Tools\AController))
  130. return false;
  131. }
  132. catch (\Exception\Error404 $e)
  133. {
  134. return false;
  135. }
  136. return $result;
  137. }
  138. /**
  139. * Check if the request match route
  140. * @param array $request User request
  141. * @param array $route Route to check
  142. * @return array on success, false on failure
  143. **/
  144. private function routeMatch($request, $route)
  145. {
  146. $i = count($request);
  147. $params = array();
  148. if ($i != count($route))
  149. return false;
  150. while ($i)
  151. {
  152. $i--;
  153. if ($route[$i] == '' && $request[$i] == '')
  154. continue;
  155. if ($route[$i] == '' || $request[$i] == '')
  156. return false;
  157. if ($route[$i][0] != ':' && ($route[$i] != $request[$i]))
  158. return false;
  159. if ($route[$i][0] == ':')
  160. $params[$route[$i]] = $request[$i];
  161. $params[$i -1] = $request[$i];
  162. }
  163. return array_reverse($params);
  164. }
  165. /**
  166. * Append local routes to router
  167. * Will load CMS pages, categories page, products page, cart pages, etc.
  168. **/
  169. private function prepareUrl()
  170. {
  171. $fetcher = new \Entity\Cms();
  172. $pages = $fetcher->selects(null, array("order"));
  173. foreach ($pages as $i)
  174. $this->doRouteAdd($i->shurl, $i->controller);
  175. }
  176. /**
  177. * Add a route to the internal route list
  178. * Internal procedure
  179. **/
  180. private function doRouteAdd($route, $controller)
  181. {
  182. $this->routes[] = array($route, $controller);
  183. }
  184. /**
  185. * @param string $route Uri to match the controller
  186. * Uri can be formatted as '/:param/static'.
  187. * expl. '/product/:id/'
  188. * @param string $controller Controller class name.
  189. * new $controller() MUST return a \Tool\AController instance
  190. *
  191. * Add a route and a Controller to the list
  192. * Can only be called from `routerSetup' hook
  193. **/
  194. public function routeAdd($route, $controller)
  195. {
  196. if (!$this->context->hookManager->isInHook("routerSetup"))
  197. throw new \Exception("You can only add routes from `routerSetup' hook");
  198. $this->doRouteAdd($route, $controller);
  199. }
  200. /**
  201. * Getter
  202. **/
  203. public function __get($key)
  204. {
  205. switch ($key)
  206. {
  207. case "rootPath": return $this->rootPath; break;
  208. case "rootUrl": return $this->rootUrl; break;
  209. case "modulesPath": return $this->rootPath."content/modules/"; break;
  210. case "modulesUrl": return $this->rootUrl."content/modules/"; break;
  211. case "themesPath": return $this->rootPath."content/theme/"; break;
  212. case "themesUrl": return $this->rootUrl."content/theme/"; break;
  213. }
  214. throw new \Exception("Cannot access attribute {$key}");
  215. }
  216. }