Guest User

Untitled

a guest
Jan 23rd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1. <?php
  2. class Router
  3. {
  4. public static $cacheRoutes = true;
  5.  
  6. public static function route($requestURI, $options = array())
  7. {
  8. if (!empty($_SERVER['QUERY_STRING'])) {
  9. $requestURI = substr($requestURI, 0, -strlen($_SERVER['QUERY_STRING']) - 1);
  10. }
  11.  
  12. // Trim the base part of the URL
  13. $requestURI = substr($requestURI, strlen(parse_url(Br_Controller::$url, PHP_URL_PATH)));
  14.  
  15. $routes = self::getRoutes();
  16.  
  17. if (isset($options['view'], $routes[$options['view']])) {
  18. $options['model'] = $routes[$options['view']];
  19. return $options;
  20. }
  21.  
  22. if (empty($requestURI)) {
  23. // Default view/homepage
  24. $options['model'] = "Home_View";
  25. return $options;
  26. }
  27.  
  28. foreach ($routes as $route_exp=>$model) {
  29. if ($route_exp[0] == '/' && preg_match($route_exp, $requestURI, $matches)) {
  30. $options += $matches;
  31. $options['model'] = $model;
  32. return $options;
  33. }
  34. }
  35.  
  36. return $options;
  37. }
  38.  
  39. public static function getRoutes()
  40. {
  41. if (!self::$cacheRoutes) {
  42. return self::compileRoutes();
  43. }
  44.  
  45. if (file_exists(self::getCachePath())) {
  46. $cache = file_get_contents(self::getCachePath());
  47. return unserialize($cache);
  48. }
  49.  
  50. return self::cacheRoutes();
  51.  
  52. }
  53.  
  54. public static function cacheRoutes()
  55. {
  56. $routes = self::compileRoutes();
  57.  
  58. file_put_contents(self::getCachePath(), serialize($routes));
  59.  
  60. return $routes;
  61. }
  62.  
  63. public static function getCachePath()
  64. {
  65. return sys_get_temp_dir() . "/" . __CLASS__ . "_Cache.php";
  66. }
  67.  
  68. public static function compileRoutes()
  69. {
  70. $routes = array();
  71.  
  72. //Directory itterator
  73. $directory = new DirectoryIterator(dirname(__FILE__));
  74.  
  75. //Compile all the routes.
  76. foreach ($directory as $file) {
  77. if ($file->getType() == 'dir' && !$file->isDot()) {
  78. $class = "Br_" . $file->getFileName() . "_Router";
  79. if (file_exists(dirname(dirname(__FILE__)) . "/" . str_replace('_', '/', $class). ".php")
  80. && class_exists($class)) {
  81. $routes += call_user_func($class . "::getRoutes");
  82. }
  83. }
  84. }
  85.  
  86. return $routes;
  87. }
  88. }
Add Comment
Please, Sign In to add comment