Router.php 9.0 KB

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