Router.php 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 array $overridden
  47. * contains url and paths to rewrite
  48. **/
  49. private $overridden;
  50. /**
  51. * @var string $modulePath
  52. * Contains the module directory
  53. **/
  54. /**
  55. * @var string $moduleUrl
  56. * Contains the module Uri
  57. **/
  58. /**
  59. * @var string $themePath
  60. * Contains the theme directory
  61. **/
  62. /**
  63. * @var string $themeUrl
  64. * Contains the theme Uri
  65. **/
  66. /**
  67. * Create the router, initialize url and path
  68. **/
  69. public function __construct($server, $context)
  70. {
  71. $pos = strrpos($server["SCRIPT_NAME"], "/");
  72. $relativePath = (($pos === FALSE) ? "" : substr($server["SCRIPT_NAME"], 0, $pos));
  73. $this->rootPath = $server["DOCUMENT_ROOT"] . $relativePath . "/";
  74. $this->rootUrl = $server["REQUEST_SCHEME"] . "://" . $server["HTTP_HOST"] . $relativePath ."/";
  75. $this->requestUrl = substr($server["REQUEST_URI"], count($this->rootUrl) -1);
  76. $this->context = $context;
  77. $this->routes = array();
  78. $this->overridden = null;
  79. }
  80. /**
  81. * Called after database initialization
  82. * Check the site url and redirect user if the HOST does not match
  83. * If the site url is not defined in database, do not redirect
  84. **/
  85. public function init($server)
  86. {
  87. $siteUrl = \Entity\Config::getConfig(null, "siteUrl");
  88. // @codeCoverageIgnoreStart
  89. // This code is tested under another process
  90. if ($siteUrl != $server["HTTP_HOST"] && $siteUrl !== null)
  91. {
  92. header("location: http://{$siteUrl}{$server['REQUEST_URI']}");
  93. die;
  94. }
  95. // @codeCoverageIgnoreEnd
  96. }
  97. /**
  98. * @return \Controller\AController controller
  99. * /core/controller/AController.php
  100. * Match request to a controller
  101. * return FALSE on failure (eg. 404)
  102. **/
  103. public function serveUrl()
  104. {
  105. $this->prepareUrl();
  106. $requestParams = explode("/", $this->requestUrl);
  107. foreach ($this->routes as $i)
  108. {
  109. $routeParams = explode("/", $i[0]);
  110. $p = $this->routeMatch($requestParams, $routeParams);
  111. if ($p === false)
  112. continue;
  113. $controller = $this->createController($i[1], $p);
  114. if ($controller)
  115. return $controller;
  116. }
  117. return false;
  118. }
  119. /**
  120. * Create and return Controller for the given route
  121. * @param $className
  122. * @param array $routeParameters
  123. * @return \Tools\AController on succes, false otherwise
  124. **/
  125. private function createController($className, $params)
  126. {
  127. if (!class_exists($className))
  128. return false;
  129. $this->routeParams = $params;
  130. $result = null;
  131. try
  132. {
  133. $result = new $className($this->context, $params);
  134. if (!($result instanceof \Tools\AController))
  135. return false;
  136. }
  137. catch (\Exception\Error404 $e)
  138. {
  139. return false;
  140. }
  141. return $result;
  142. }
  143. /**
  144. * Check if the request match route
  145. * @param array $request User request
  146. * @param array $route Route to check
  147. * @return array on success, false on failure
  148. **/
  149. private function routeMatch($request, $route)
  150. {
  151. $i = count($request);
  152. $params = array();
  153. if ($i != count($route))
  154. return false;
  155. while ($i)
  156. {
  157. $i--;
  158. if ($route[$i] == '' && $request[$i] == '')
  159. continue;
  160. if ($route[$i] == '' || $request[$i] == '')
  161. return false;
  162. if ($route[$i][0] != ':' && ($route[$i] != $request[$i]))
  163. return false;
  164. if ($route[$i][0] == ':')
  165. $params[$route[$i]] = $request[$i];
  166. $params[$i -1] = $request[$i];
  167. }
  168. return array_reverse($params);
  169. }
  170. /**
  171. * Append local routes to router
  172. * Will load CMS pages, categories page, products page, cart pages, etc.
  173. **/
  174. private function prepareUrl()
  175. {
  176. $fetcher = new \Entity\Cms();
  177. $pages = $fetcher->selects(null, array("order"));
  178. foreach ($pages as $i)
  179. $this->doRouteAdd($i->shurl, $i->controller);
  180. }
  181. /**
  182. * Add a route to the internal route list
  183. * Internal procedure
  184. **/
  185. private function doRouteAdd($route, $controller)
  186. {
  187. $this->routes[] = array($route, $controller);
  188. }
  189. /**
  190. * @param string $route Uri to match the controller
  191. * Uri can be formatted as '/:param/static'.
  192. * expl. '/product/:id/'
  193. * @param string $controller Controller class name.
  194. * new $controller() MUST return a \Tool\AController instance
  195. *
  196. * Add a route and a Controller to the list
  197. * Can only be called from `routerSetup' hook
  198. **/
  199. public function routeAdd($route, $controller)
  200. {
  201. if (!$this->context->hookManager->isInHook("routerSetup"))
  202. throw new \Exception("You can only add routes from `routerSetup' hook");
  203. $this->doRouteAdd($route, $controller);
  204. }
  205. /**
  206. * Override url
  207. * This SHOULD not be called for security purpose
  208. * @param string $type the url type to override
  209. * @param string $value the new value
  210. * Will fail if called from a controller
  211. * @return boolean false on failure
  212. **/
  213. public function overrideUrl($type, $value)
  214. {
  215. if (!$this->context->isTestingEnvironment())
  216. return false;
  217. $this->overridden[$type] = $value;
  218. return true;
  219. }
  220. /**
  221. * Getter
  222. **/
  223. public function __get($key)
  224. {
  225. if (isset($this->overridden) && in_array($key, array("modulesPath")))
  226. return $this->overridden[$key];
  227. switch ($key)
  228. {
  229. case "rootPath": return $this->rootPath; break;
  230. case "rootUrl": return $this->rootUrl; break;
  231. case "modulesPath": return $this->rootPath."content/modules/"; break;
  232. case "modulesUrl": return $this->rootUrl."content/modules/"; break;
  233. case "themesPath": return $this->rootPath."content/theme/"; break;
  234. case "themesUrl": return $this->rootUrl."content/theme/"; break;
  235. }
  236. throw new \Exception("Cannot access attribute {$key}");
  237. }
  238. }