router.php 2.35 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php namespace System;

class Router {

	/**
	 * All of the loaded routes.
	 *
	 * @var array
	 */
	public static $routes;

	/**
	 * Search a set of routes for the route matching a method and URI.
	 *
	 * @param  string  $method
	 * @param  string  $uri
	 * @return Route
	 */
	public static function route($method, $uri)
	{
21
		// Prepend a forward slash since all routes begin with one.
22 23
		$uri = ($uri != '/') ? '/'.$uri : $uri;

24
		if (is_null(static::$routes))
25
		{
26
			static::$routes = (is_dir(APP_PATH.'routes')) ? static::load($uri) : require APP_PATH.'routes'.EXT;
27
		}
28 29 30 31

		// Is there an exact match for the request?
		if (isset(static::$routes[$method.' '.$uri]))
		{
32
			return Request::$route = new Route($method.' '.$uri, static::$routes[$method.' '.$uri]);
33 34 35 36
		}

		foreach (static::$routes as $keys => $callback)
		{
Taylor Otwell committed
37 38
			// Only check routes that have multiple URIs or wildcards. All other routes would
			// have been caught by a literal match.
39 40
			if (strpos($keys, '(') !== false or strpos($keys, ',') !== false )
			{
41
				foreach (explode(', ', $keys) as $key)
42
				{
43
					$key = str_replace(':num', '[0-9]+', str_replace(':any', '[a-zA-Z0-9\-_]+', $key));
44

45
					if (preg_match('#^'.$key.'$#', $method.' '.$uri))
46
					{
47
						return Request::$route = new Route($keys, $callback, static::parameters($uri, $key));
48 49 50 51 52 53
					}
				}				
			}
		}
	}

54 55 56 57 58 59
	/**
	 * Load the appropriate route file for the request URI.
	 *
	 * @param  string  $uri
	 * @return array
	 */
60
	public static function load($uri)
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
	{
		if ( ! file_exists(APP_PATH.'routes/home'.EXT))
		{
			throw new \Exception("A [home] route file is required when using a route directory.");					
		}

		if ($uri == '/')
		{
			return require APP_PATH.'routes/home'.EXT;
		}
		else
		{
			$segments = explode('/', trim($uri, '/'));

			if ( ! file_exists(APP_PATH.'routes/'.$segments[0].EXT))
			{
				return require APP_PATH.'routes/home'.EXT;
			}

			return array_merge(require APP_PATH.'routes/'.$segments[0].EXT, require APP_PATH.'routes/home'.EXT);
		}
	}

	/**
	 * Extract the parameters from a URI based on a route URI.
	 *
	 * Any route segment wrapped in parentheses is considered a parameter.
	 *
89 90
	 * @param  string  $uri
	 * @param  string  $route
91 92 93 94
	 * @return array
	 */
	private static function parameters($uri, $route)
	{
95
		return array_values(array_intersect_key(explode('/', $uri), preg_grep('/\(.+\)/', explode('/', $route))));	
96 97
	}	

98
}