RouteCollection.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. <?php
  2. namespace Routes;
  3. class RouteCollection {
  4. private static $_routeCollection;
  5. public $_uri = '/';
  6. public $_routes = Array();
  7. private $_verb = '';
  8. private $_loadedFiles = Array();
  9. private $_errors = Array();
  10. private $_defaultMiddlewares = Array();
  11. private $_middlewareSet = Array();
  12. private static $_verbsWhitelist = Array('*', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'CLI');
  13. private static $_verbsWeb = Array('GET', 'POST', 'PUT', 'PATCH', 'DELETE');
  14. public $_groupIn = false;
  15. public $_groupBase = '';
  16. public $_groupList = [];
  17. //SINGLETON==============================================
  18. private function __construct() {
  19. }
  20. private static function newObj() {
  21. if (!isset(self::$_routeCollection)) {
  22. self::$_routeCollection = new RouteCollection();
  23. if (php_sapi_name() == "cli") {
  24. self::$_routeCollection->_uri = isset($_SERVER['argv'][1]) ? '/' . $_SERVER['argv'][1] : '/';
  25. } else {
  26. self::$_routeCollection->_uri = isset($_SERVER['REQUEST_URI']) ? explode('?', $_SERVER['REQUEST_URI'])[0] : '/';
  27. }
  28. self::$_routeCollection->defineVerb();
  29. }
  30. self::$_routeCollection->_uri = str_replace("//", "/", self::$_routeCollection->_uri);
  31. return self::$_routeCollection;
  32. }
  33. /**
  34. *
  35. */
  36. public static function getInstance() {
  37. if (!isset(self::$_routeCollection)) {
  38. return self::newObj();
  39. }
  40. return self::$_routeCollection;
  41. }
  42. //HELPERS================================================
  43. /*
  44. * Find route files with names under pathname
  45. *
  46. * @ctag\t RouteCollection->crawl()
  47. */
  48. public function crawl($basepath = __DIR__, $filenames = Array('Routes.php', 'routes.php')) {
  49. $instance = self::getInstance();
  50. $rdi = new \RecursiveDirectoryIterator($basepath);
  51. foreach (new \RecursiveIteratorIterator($rdi) as $file) {
  52. foreach ($filenames as $filename) {
  53. if (strpos($file, $filename)) {
  54. $instance->_loadedFiles[] = $file;
  55. }
  56. }
  57. }
  58. return $instance;
  59. }
  60. /**
  61. *
  62. * Load the files with the routes
  63. * @ctag\t RouteCollection->loadRoutes()
  64. */
  65. function loadRoutes() {
  66. $instance = self::getInstance();
  67. foreach ($instance->_loadedFiles as $loadedFile) {
  68. include $loadedFile;
  69. }
  70. return $instance;
  71. }
  72. /**
  73. *
  74. * GET | POST | PUT | PATCH | DELETE | CLI
  75. *
  76. */
  77. private function defineVerb() {
  78. $verb = '';
  79. if (isset($_POST['_method'])) {
  80. $verb = strtoupper($_POST['_method']);
  81. } else if (php_sapi_name() == "cli") {
  82. $verb = "CLI";
  83. } else {
  84. $verb = strtoupper($_SERVER['REQUEST_METHOD']);
  85. }
  86. if (in_array($verb, self::$_verbsWhitelist)) {
  87. $this->_verb = $verb;
  88. } else {
  89. echo 'Invalid Verb';
  90. }
  91. }
  92. /**
  93. *
  94. */
  95. private function sort_routes() {
  96. usort($this->_routes, function($a, $b) {
  97. if ($a->_weight == $b->_weight) {
  98. return 0;
  99. }
  100. return ($a->_weight < $b->_weight) ? -1 : 1;
  101. });
  102. }
  103. /**
  104. *
  105. */
  106. function submit() {
  107. global $ROUTE;
  108. self::$_routeCollection->sort_routes();
  109. $one_hit = false;
  110. foreach (self::$_routeCollection->_routes as $route) {
  111. if (!in_array(self::$_routeCollection->_verb, $route->_verb) && !in_array('*', $route->_verb)) {
  112. //No it is not
  113. continue;
  114. }
  115. //Request match a route
  116. $match = $route->match(self::$_routeCollection->_uri);
  117. if ($match) {
  118. //Yup. Execute the route
  119. $ROUTE = $route;
  120. $route->_before = $this->_defaultMiddlewares;
  121. $route->execute();
  122. if (!$route->_ignore) {
  123. $one_hit = true;
  124. }
  125. if ($route->_httpError) {
  126. $this->httpError($route->_httpError);
  127. return;
  128. }
  129. //If Executed, interrupt route chain?
  130. if ($route->_block) {
  131. return;
  132. }
  133. }
  134. }
  135. if (!$one_hit) {
  136. $info = new \stdClass();
  137. $info->code = 404;
  138. $info->message = 'Not Found';
  139. self::$_routeCollection->httpError($info);
  140. }
  141. }
  142. /**
  143. *
  144. * @ctag RouteCollection::group('base',function(){})
  145. */
  146. static function group($base = '', $callback){
  147. $collection = self::getInstance();
  148. $collection->_groupList = [];
  149. $collection->_groupIn = true;
  150. $collection->_groupBase = $base;
  151. call_user_func($callback);
  152. $collection->_groupBase = '';
  153. $collection->_groupIn = false;
  154. return new RouteGroup($collection->_groupList);
  155. }
  156. //DEFINITORS=============================================
  157. /**
  158. *
  159. * @ctag RouteCollection::get('/url',function(){})
  160. */
  161. static function get($uri, $callback, $weight = 0) {
  162. return self::add('GET', $uri, $callback, $weight);
  163. }
  164. /**
  165. *
  166. * @ctag RouteCollection::cli('/url',function(){})
  167. */
  168. static function cli($uri, $callback, $weight = 0) {
  169. return self::add('CLI', $uri, $callback, $weight);
  170. }
  171. /**
  172. *
  173. * @ctag RouteCollection::post('/url',function(){})
  174. */
  175. static function post($uri, $callback, $weight = 0) {
  176. return self::add('POST', $uri, $callback, $weight);
  177. }
  178. /**
  179. *
  180. * @ctag RouteCollection::put('/url',function(){})
  181. */
  182. static function put($uri, $callback, $weight = 0) {
  183. return self::add('PUT', $uri, $callback, $weight);
  184. }
  185. /**
  186. *
  187. * @ctag RouteCollection::patch('/url',function(){})
  188. */
  189. static function patch($uri, $callback, $weight = 0) {
  190. return self::add('PATCH', $uri, $callback, $weight);
  191. }
  192. /**
  193. *
  194. * @ctag RouteCollection::delete('/url',Controller@Method)
  195. * @ctag RouteCollection::delete('/url',function(){})
  196. */
  197. static function delete($uri, $callback, $weight = 0) {
  198. return self::add('DELETE', $uri, $callback, $weight);
  199. }
  200. /**
  201. *
  202. * @ctag RouteCollection::resource('/url',function(){})
  203. */
  204. static function resource($uri) {
  205. throw new Exception('Not implemented');
  206. }
  207. /**
  208. *
  209. * @ctag RouteCollection::add('VERB','/url',function(){})
  210. * @ctag RouteCollection::add('VERB','/url',Controller@Method)
  211. */
  212. static function add($verb, $uri, $callback, $weight = 0) {
  213. $route = new Route();
  214. if(self::getInstance()->_groupIn){
  215. $uri = self::getInstance()->_groupBase . $uri;
  216. self::getInstance()->_groupList[] = &$route;
  217. }
  218. $uri = rtrim($uri, '/');
  219. if (is_array($verb)) {
  220. $route->_verb = array_map('strtoupper', $verb);
  221. } else if (strtoupper($verb) == 'WEB') {
  222. $route->_verb[] = self::_verbsWeb;
  223. } else {
  224. $route->_verb[] = strtoupper($verb);
  225. }
  226. $route->_uri = $uri;
  227. $route->_callback[] = $callback;
  228. $route->_weight = $weight;
  229. $route->prepare();
  230. self::getInstance()->_routes[] = $route;
  231. return $route;
  232. }
  233. /**
  234. *
  235. */
  236. function addRoute(Route $route) {
  237. $this->_routes[] = $route;
  238. }
  239. /**
  240. *
  241. * @ctag RouteCollection::addDefaultMiddleware('name',function(){})
  242. */
  243. static function addDefaultMiddleware($name = '', $function) {
  244. self::getInstance()->_defaultMiddlewares[$name] = $function;
  245. }
  246. /**
  247. *
  248. * @ctag RouteCollection::addDefaultMiddleware('name',function(){})
  249. */
  250. static function registerMiddleware($name = '', $function) {
  251. self::getInstance()->_middlewareSet[$name] = $function;
  252. }
  253. /**
  254. *
  255. * @ctag RouteCollection::onHttpError(function(){})
  256. */
  257. static function onHttpError($function) {
  258. $instance = self::getInstance();
  259. $instance->_errors[] = $function;
  260. }
  261. /**
  262. *
  263. * @ctag RouteCollection::httpError($class)
  264. */
  265. private function httpError(\stdClass $info) {
  266. $info = (array) $info;
  267. foreach ($this->_errors as $error) {
  268. call_user_func_array($error, $info);
  269. }
  270. }
  271. }