router.php 3.17 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
		if (is_null(static::$routes))
22
		{
23
			static::$routes = static::load($uri);
24
		}
25

Taylor Otwell committed
26 27
		// Put the request method and URI in route form. 
		// Routes begin with the request method and a forward slash.
28 29
		$uri = $method.' /'.trim($uri, '/');

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

		foreach (static::$routes as $keys => $callback)
		{
Taylor Otwell committed
38 39
			// Only check routes that have multiple URIs or wildcards.
			// Other routes would have been caught by the check for literal matches.
40 41
			if (strpos($keys, '(') !== false or strpos($keys, ',') !== false )
			{
42
				foreach (explode(', ', $keys) as $key)
43
				{
44
					if (preg_match('#^'.static::translate_wildcards($key).'$#', $uri))
45
					{
46
						return Request::$route = new Route($keys, $callback, static::parameters($uri, $key));
47 48 49 50 51 52
					}
				}				
			}
		}
	}

53 54 55 56 57 58
	/**
	 * Load the appropriate route file for the request URI.
	 *
	 * @param  string  $uri
	 * @return array
	 */
59
	public static function load($uri)
60
	{
61 62 63
		$base = require APP_PATH.'routes'.EXT;

		return (is_dir(APP_PATH.'routes') and $uri !== '') ? array_merge(static::load_from_directory($uri), $base) : $base;
Taylor Otwell committed
64
	}
65

Taylor Otwell committed
66 67 68 69 70 71 72 73 74
	/**
	 * Load the appropriate route file from the routes directory.
	 *
	 * @param  string  $uri
	 * @return array
	 */
	private static function load_from_directory($uri)
	{
		$segments = explode('/', $uri);
75

76 77
		// Route files can be nested deep within sub-directories. 
		// Iterate backwards through the URI looking for the deepest matching file.
78 79 80 81 82 83 84 85 86
		foreach (array_reverse($segments, true) as $key => $value)
		{
			if (file_exists($path = APP_PATH.'routes/'.implode('/', array_slice($segments, 0, $key + 1)).EXT))
			{
				return require $path;
			}
		}

		return array();
87 88 89
	}

	/**
90
	 * Translate route URI wildcards into actual regular expressions.
91 92 93 94 95 96
	 *
	 * @param  string  $key
	 * @return string
	 */
	private static function translate_wildcards($key)
	{
97 98 99 100 101 102 103 104
		$replacements = 0;

		// For optional parameters, first translate the wildcards to their regex equivalent, sans the ")?" ending.
		$key = str_replace(array('/(:num?)', '/(:any?)'), array('(?:/([0-9]+)', '(?:/([a-zA-Z0-9\-_]+)'), $key, $replacements);
		
		// Now, to properly close the regular expression, we need to append a ")?" for each optional segment in the route.
		if ($replacements > 0)
		{
Taylor Otwell committed
105
			$key .= str_repeat(')?', $replacements);
106 107 108
		}

		return str_replace(array(':num', ':any'), array('[0-9]+', '[a-zA-Z0-9\-_]+'), $key);
109 110 111
	}

	/**
112 113 114 115
	 * Extract the parameters from a URI based on a route URI.
	 *
	 * Any route segment wrapped in parentheses is considered a parameter.
	 *
116 117
	 * @param  string  $uri
	 * @param  string  $route
118 119
	 * @return array
	 */
120
	private static function parameters($uri, $route)
121
	{
122
		return array_values(array_intersect_key(explode('/', $uri), preg_grep('/\(.+\)/', explode('/', $route))));	
123 124
	}	

125
}