uri.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. <?php namespace Laravel;
  2. class URI {
  3. /**
  4. * The URI for the current request.
  5. *
  6. * @var string
  7. */
  8. public static $uri;
  9. /**
  10. * The URI segments for the current request.
  11. *
  12. * @var array
  13. */
  14. public static $segments = array();
  15. /**
  16. * Get the URI for the current request.
  17. *
  18. * @return string
  19. */
  20. public static function current()
  21. {
  22. if ( ! is_null(static::$uri)) return static::$uri;
  23. $uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
  24. // Remove the root application URL from the request URI. If the application
  25. // is nested within a sub-directory of the web document root, this will get
  26. // rid of all of the the sub-directories from the request URI.
  27. $uri = static::remove($uri, parse_url(URL::base(), PHP_URL_PATH));
  28. // We'll also remove the application's index page as it is not used for at
  29. // all for routing and is totally unnecessary as far as the routing of
  30. // incoming requests to the framework is concerned.
  31. if (($index = '/'.Config::get('application.index')) !== '/')
  32. {
  33. $uri = static::remove($uri, $index);
  34. }
  35. static::segments(static::$uri = static::format($uri));
  36. return static::$uri;
  37. }
  38. /**
  39. * Get a specific segment of the request URI via an one-based index.
  40. *
  41. * <code>
  42. * // Get the first segment of the request URI
  43. * $segment = URI::segment(1);
  44. *
  45. * // Get the second segment of the URI, or return a default value
  46. * $segment = URI::segment(2, 'Taylor');
  47. * </code>
  48. *
  49. * @param int $index
  50. * @param mixed $default
  51. * @return string
  52. */
  53. public static function segment($index, $default = null)
  54. {
  55. static::current();
  56. return array_get(static::$segments, $index - 1, $default);
  57. }
  58. /**
  59. * Set the URI segments for the request.
  60. *
  61. * @param string $uri
  62. * @return void
  63. */
  64. protected static function segments($uri)
  65. {
  66. $segments = explode('/', trim($uri, '/'));
  67. static::$segments = array_diff($segments, array(''));
  68. }
  69. /**
  70. * Remove a given value from the URI.
  71. *
  72. * @param string $uri
  73. * @param string $value
  74. * @return string
  75. */
  76. protected static function remove($uri, $value)
  77. {
  78. return (strpos($uri, $value) === 0) ? substr($uri, strlen($value)) : $uri;
  79. }
  80. /**
  81. * Format a given URI.
  82. *
  83. * @param string $uri
  84. * @return string
  85. */
  86. protected static function format($uri)
  87. {
  88. return (($uri = trim($uri, '/')) !== '') ? $uri : '/';
  89. }
  90. }