uri.php 2.46 KB
Newer Older
1 2 3 4 5 6 7 8 9
<?php namespace Laravel;

class URI {

	/**
	 * The URI for the current request.
	 *
	 * @var string
	 */
Taylor Otwell committed
10
	public static $uri;
11 12 13 14 15 16

	/**
	 * The URI segments for the current request.
	 *
	 * @var array
	 */
17
	public static $segments = array();
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

	/**
	 * Get the URI for the current request.
	 *
	 * @return string
	 */
	public static function current()
	{
		if ( ! is_null(static::$uri)) return static::$uri;

		$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

		// Remove the root application URL from the request URI. If the application
		// is nested within a sub-directory of the web document root, this will get
		// rid of all of the the sub-directories from the request URI.
33
		$uri = static::remove($uri, parse_url(URL::base(), PHP_URL_PATH));
34

35 36 37 38
		// We'll also remove the application's index page as it is not used for at
		// all for routing and is totally unnecessary as far as the framework is
		// concerned. It is only in the URI when mod_rewrite is not available.
		if (($index = '/'.Config::get('application.index')) !== '/')
39 40 41 42
		{
			$uri = static::remove($uri, $index);
		}

Taylor Otwell committed
43
		static::$uri = static::format($uri);
44

45 46 47 48 49 50 51
		// Cache the URI segments. This allows us to avoid having to explode
		// the segments every time the developer requests one of them. The
		// extra slashes have already been stripped off of the URI so no
		// extraneous elements should be present in the segment array.
		$segments = explode('/', trim(static::$uri, '/'));

		static::$segments = array_diff($segments, array(''));
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74

		return static::$uri;
	}

	/**
	 * Get a specific segment of the request URI via an one-based index.
	 *
	 * <code>
	 *		// Get the first segment of the request URI
	 *		$segment = URI::segment(1);
	 *
	 *		// Get the second segment of the URI, or return a default value
	 *		$segment = URI::segment(2, 'Taylor');
	 * </code>
	 *
	 * @param  int     $index
	 * @param  mixed   $default
	 * @return string
	 */
	public static function segment($index, $default = null)
	{
		static::current();

75
		return array_get(static::$segments, $index - 1, $default);
76 77 78 79 80 81 82 83 84 85 86
	}

	/**
	 * Remove a given value from the URI.
	 *
	 * @param  string  $uri
	 * @param  string  $value
	 * @return string
	 */
	protected static function remove($uri, $value)
	{
87
		return (strpos($uri, $value) === 0) ? substr($uri, strlen($value)) : $uri;
88 89 90 91 92 93 94 95 96 97 98 99 100 101
	}

	/**
	 * Format a given URI.
	 *
	 * @param  string  $uri
	 * @return string
	 */
	protected static function format($uri)
	{
		return (($uri = trim($uri, '/')) !== '') ? $uri : '/';
	}

}