loader.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php namespace System\Routing;
  2. class Loader {
  3. /**
  4. * All of the routes for the application.
  5. *
  6. * @var array
  7. */
  8. private static $routes;
  9. /**
  10. * Load the appropriate routes for the request URI.
  11. *
  12. * @param string
  13. * @return array
  14. */
  15. public function load($uri)
  16. {
  17. $base = require APP_PATH.'routes'.EXT;
  18. return (is_dir(APP_PATH.'routes') and $uri != '') ? array_merge($this->load_nested_routes($uri), $base) : $base;
  19. }
  20. /**
  21. * Load the appropriate routes from the routes directory.
  22. *
  23. * @param string $uri
  24. * @return array
  25. */
  26. private function load_nested_routes($uri)
  27. {
  28. $segments = explode('/', $uri);
  29. // Work backwards through the URI segments until we find the deepest possible
  30. // matching route file in the routes directory.
  31. foreach (array_reverse($segments, true) as $key => $value)
  32. {
  33. if (file_exists($path = ROUTE_PATH.implode('/', array_slice($segments, 0, $key + 1)).EXT))
  34. {
  35. return require $path;
  36. }
  37. }
  38. return array();
  39. }
  40. /**
  41. * Get all of the routes for the application.
  42. *
  43. * To improve performance, this operation will only be performed once. The routes
  44. * will be cached and returned on every subsequent call.
  45. *
  46. * @return array
  47. */
  48. public static function everything()
  49. {
  50. if ( ! is_null(static::$routes)) return static::$routes;
  51. $routes = require APP_PATH.'routes'.EXT;
  52. if (is_dir(APP_PATH.'routes'))
  53. {
  54. // Since route files can be nested deep within the route directory, we need to
  55. // recursively spin through the directory to find every file.
  56. $directoryIterator = new \RecursiveDirectoryIterator(APP_PATH.'routes');
  57. $recursiveIterator = new \RecursiveIteratorIterator($directoryIterator, \RecursiveIteratorIterator::SELF_FIRST);
  58. foreach ($recursiveIterator as $file)
  59. {
  60. if (filetype($file) === 'file' and strpos($file, EXT) !== false)
  61. {
  62. $routes = array_merge(require $file, $routes);
  63. }
  64. }
  65. }
  66. return static::$routes = $routes;
  67. }
  68. }