Router.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. <?php
  2. namespace KarmaFW\Routing;
  3. use \KarmaFW\WebApp;
  4. use \KarmaFW\Http\Request;
  5. use \KarmaFW\Http\Response;
  6. class Router
  7. {
  8. private static $routes = [];
  9. private static $routed_url = null;
  10. private static $config = [];
  11. public static function config($config)
  12. {
  13. self::$config = $config;
  14. }
  15. public static function setConfig($key, $value)
  16. {
  17. self::$config[$key] = $value;
  18. }
  19. public static function getConfig($key)
  20. {
  21. return self::$config[$key];
  22. }
  23. public static function group($config, $callable)
  24. {
  25. $old_config = self::$config;
  26. self::$config = $config;
  27. $callable();
  28. self::$config = $old_config;
  29. }
  30. // Register a route in the router
  31. public static function add($methods, $url_match, $callback=null, $type_match='exact', $regex_params=[])
  32. {
  33. $route = new Route();
  34. if (! empty(self::$config['prefix'])) {
  35. // ex: $prefix == "/fr"
  36. $route->setPrefix(self::$config['prefix'], 'exact', self::$config['prefix']);
  37. } else if (! empty(self::$config['prefix_regex'])) {
  38. // ex: $prefix == "/[a-zA-Z0-9-]+"
  39. $get_prefix = empty(self::$config['get_prefix']) ? null : self::$config['get_prefix'];
  40. $route->setPrefix(self::$config['prefix_regex'], 'regex', $get_prefix);
  41. } else if (! empty(self::$config['prefix_array'])) {
  42. // ex: $prefix == ["/fr", "/us"]
  43. $get_prefix = empty(self::$config['get_prefix']) ? null : self::$config['get_prefix'];
  44. $route->setPrefix(self::$config['prefix_array'], 'array', $get_prefix);
  45. }
  46. if (! empty(self::$config['before_callback'])) {
  47. $route->setBeforeCallback(self::$config['before_callback']);
  48. }
  49. $route->setMatchUrl($url_match);
  50. $route->setCallback($callback);
  51. $route->setMatchType($type_match);
  52. $route->setRegexParams($regex_params);
  53. if (! is_array($methods)) {
  54. $methods = [$methods];
  55. }
  56. foreach ($methods as $method) {
  57. $route->setMethod($method);
  58. }
  59. self::$routes[] = $route;
  60. return $route;
  61. }
  62. public static function error404($callback=null)
  63. {
  64. // todo: faire en sorte qu'elle soit executée en dernier
  65. return self::all('.*', $callback, 'regex');
  66. }
  67. // Allow whatever method (GET, POST, HEAD, OPTION, DELETE, PUT, ...)
  68. public static function all($url_match, $callback=null, $type_match='exact', $regex_params=[])
  69. {
  70. return self::Add(null, $url_match, $callback, $type_match, $regex_params);
  71. }
  72. // GET method
  73. public static function get($url_match, $callback=null, $type_match='exact', $regex_params=[])
  74. {
  75. return self::Add('GET', $url_match, $callback, $type_match, $regex_params);
  76. }
  77. // POST method
  78. public static function post($url_match, $callback=null, $type_match='exact', $regex_params=[])
  79. {
  80. return self::Add('POST', $url_match, $callback, $type_match, $regex_params);
  81. }
  82. // DELETE method
  83. public static function delete($url_match, $callback=null, $type_match='exact', $regex_params=[])
  84. {
  85. return self::Add('DELETE', $url_match, $callback, $type_match, $regex_params);
  86. }
  87. // PUT method
  88. public static function put($url_match, $callback=null, $type_match='exact', $regex_params=[])
  89. {
  90. return self::Add('PUT', $url_match, $callback, $type_match, $regex_params);
  91. }
  92. // HEAD method
  93. public static function head($url_match, $callback=null, $type_match='exact', $regex_params=[])
  94. {
  95. return self::Add('HEAD', $url_match, $callback, $type_match, $regex_params);
  96. }
  97. // PATCH method
  98. public static function patch($url_match, $callback=null, $type_match='exact', $regex_params=[])
  99. {
  100. return self::Add('PATCH', $url_match, $callback, $type_match, $regex_params);
  101. }
  102. // OPTIONS method
  103. public static function options($url_match, $callback=null, $type_match='exact', $regex_params=[])
  104. {
  105. return self::Add('OPTIONS', $url_match, $callback, $type_match, $regex_params);
  106. }
  107. // Lookup the first matching route then execute it
  108. public static function routeByUrl($request_method, $request_uri, $debug = false, $response = null)
  109. {
  110. foreach (self::$routes as $route) {
  111. if ($debug) {
  112. pre($route);
  113. }
  114. $route->setCalledMethod($request_method);
  115. $route->setCalledUrl($request_uri);
  116. $match = $route->match($request_method, $request_uri);
  117. if ($match) {
  118. if ($debug) {
  119. echo " => MATCH !<br />" . PHP_EOL;
  120. }
  121. $before_callback = $route->getBeforeCallback();
  122. if (! empty($before_callback)) {
  123. $before_callback($route);
  124. }
  125. $callback = $route->getCallback();
  126. if (empty($callback)) {
  127. // Do nothing
  128. return 0;
  129. } else if (is_callable($callback)) {
  130. self::$routed_url = $route;
  131. self::routeRun($route, $callback, $request_method, $request_uri, $response);
  132. } else {
  133. // Error: callback not callable
  134. return null;
  135. }
  136. return $route;
  137. }
  138. }
  139. // No matching route
  140. return false;
  141. }
  142. public static function routeRun($route, $callback, $request_method, $request_uri, $response=null)
  143. {
  144. $matched_params = $route->getMatchedParams();
  145. if (gettype($callback) == 'array') {
  146. //echo " => ARRAY !<br />" . PHP_EOL;
  147. //pre($callback, 1);
  148. $controller = new $callback[0]($request_uri, $request_method, $route, $response);
  149. WebApp::$controller = $controller;
  150. call_user_func([$controller, $callback[1]], $matched_params);
  151. } else {
  152. //echo " => FUNCTION !<br />" . PHP_EOL;
  153. //pre($callback, 1);
  154. $callback($request_uri, $request_method, $route, $matched_params, $response);
  155. }
  156. return true;
  157. }
  158. public static function routeRequest(Request $request, Response $response)
  159. {
  160. $request_method = $request->getMethod();
  161. $request_uri = $request->getUrl();
  162. foreach (self::$routes as $route) {
  163. $route->setCalledMethod($request_method);
  164. $route->setCalledUrl($request_uri);
  165. $match = $route->match($request_method, $request_uri);
  166. if ($match) {
  167. $request->setRoute($route);
  168. $before_callback = $route->getBeforeCallback();
  169. if (! empty($before_callback)) {
  170. $before_callback($route);
  171. }
  172. $callback = $route->getCallback();
  173. if (empty($callback)) {
  174. // route found but no callback defined
  175. //return 0;
  176. return $response->setHtml('<h1>Page not Found</h1><p>Warning: route found but no callback defined</p>', 404);
  177. } else if (is_callable($callback)) {
  178. // OK !
  179. self::$routed_url = $route;
  180. $response = self::requestRouteRun($route, $callback, $request, $response);
  181. return $response;
  182. } else {
  183. // route found but callback is not callable
  184. //return null;
  185. return $response->setHtml('<h1>Page not Found</h1><p>Warning: route callback is not callable</p>', 404);
  186. }
  187. }
  188. }
  189. // no matching route
  190. //return false;
  191. return $response->setHtml('<h1>Page not Found</h1><p>Warning: no matching route</p>', 404);
  192. }
  193. public static function requestRouteRun(Route $route, callable $callback, Request $request, Response $response)
  194. {
  195. $matched_params = $route->getMatchedParams();
  196. if (gettype($callback) == 'array') {
  197. //echo " => ARRAY !<br />" . PHP_EOL;
  198. //pre($callback, 1);
  199. $controller = new $callback[0]($request, $response);
  200. WebApp::$controller = $controller;
  201. $route_response = call_user_func([$controller, $callback[1]], $matched_params);
  202. } else {
  203. //echo " => FUNCTION !<br />" . PHP_EOL;
  204. //pre($callback, 1);
  205. $route_response = $callback($request, $response, $matched_params);
  206. }
  207. if (is_object($route_response) && get_class($route_response) === Response::class) {
  208. $response = $route_response;
  209. } else if ($route_response) {
  210. return $response->setHtml('<html><body><h1>Server Error</h1><p>Error: $response is not a Response</p></body></html>', 404);
  211. } else {
  212. if (! $response->getContentLength()) {
  213. return $response->setHtml('<html><body><h1>Server Error</h1><p>Error: $response is empty</p></body></html>', 404);
  214. }
  215. }
  216. return $response;
  217. }
  218. // Search a route by its name
  219. public static function findRouteByName($expected_route_name, $debug = false)
  220. {
  221. if (empty($expected_route_name)) {
  222. return null;
  223. }
  224. foreach (self::$routes as $route) {
  225. $route_name = $route->getName();
  226. if (! empty($route_name) && $route_name == $expected_route_name) {
  227. return $route;
  228. }
  229. }
  230. return null;
  231. }
  232. public static function getRouteUrl($route_name, $urls_args=[])
  233. {
  234. if (empty($urls_args)) {
  235. $urls_args = array();
  236. }
  237. if (! is_array($urls_args)) {
  238. $urls_args = array($urls_args);
  239. }
  240. $route = Router::findRouteByName($route_name);
  241. if (empty($route) || $route === true) {
  242. return null;
  243. }
  244. //pre($route, 1);
  245. $get_prefix = $route->getCallbackGetPrefix();
  246. //pre($get_prefix, 0, 'get_prefix: ');
  247. $link = $route->getMatchUrl();
  248. if ($get_prefix) {
  249. $link = $get_prefix . $link;
  250. }
  251. //pre($link, 1, 'link: ');
  252. $link = rtrim($link, '$');
  253. $link = ltrim($link, '^');
  254. $link = str_replace('\\.', '.', $link);
  255. $link = str_replace('\\?', '?', $link);
  256. $link = str_replace('\\+', '+', $link);
  257. $link = str_replace('\\-', '-', $link);
  258. if (! empty($urls_args)) {
  259. foreach ($urls_args as $arg_value) {
  260. $pos1 = strpos($link, '(');
  261. if ($pos1 === false) {
  262. break;
  263. }
  264. $pos2 = strpos($link, ')', $pos1);
  265. if ($pos2 === false) {
  266. break;
  267. }
  268. $link = substr($link, 0, $pos1) . $arg_value . substr($link, $pos2+1);
  269. }
  270. }
  271. return $link;
  272. }
  273. public static function printRoutes()
  274. {
  275. dump(self::$routes);
  276. exit;
  277. }
  278. public static function getRoutedUrl()
  279. {
  280. return self::$routed_url;
  281. }
  282. }