router.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php namespace Laravel\Routing; use Closure, Laravel\Str, Laravel\Bundle;
  2. class Router {
  3. /**
  4. * All of the routes that have been registered.
  5. *
  6. * @var array
  7. */
  8. public static $routes = array();
  9. /**
  10. * All of the route names that have been matched with URIs.
  11. *
  12. * @var array
  13. */
  14. public static $names = array();
  15. /**
  16. * The wildcard patterns supported by the router.
  17. *
  18. * @var array
  19. */
  20. public static $patterns = array(
  21. '(:num)' => '([0-9]+)',
  22. '(:any)' => '([a-zA-Z0-9\.\-_]+)',
  23. );
  24. /**
  25. * The optional wildcard patterns supported by the router.
  26. *
  27. * @var array
  28. */
  29. public static $optional = array(
  30. '/(:num?)' => '(?:/([0-9]+)',
  31. '/(:any?)' => '(?:/([a-zA-Z0-9\.\-_]+)',
  32. );
  33. /**
  34. * Register a route with the router.
  35. *
  36. * <code>
  37. * // Register a route with the router
  38. * Router::register('GET /', function() {return 'Home!';});
  39. *
  40. * // Register a route that handles multiple URIs with the router
  41. * Router::register(array('GET /', 'GET /home'), function() {return 'Home!';});
  42. * </code>
  43. *
  44. * @param string|array $route
  45. * @param string $action
  46. * @return void
  47. */
  48. public static function register($route, $action)
  49. {
  50. foreach ((array) $route as $uri)
  51. {
  52. // If the action is a string, it is a pointer to a controller, so we
  53. // need to add it to the action array as a "uses" clause, which will
  54. // indicate to the route to call the controller when the route is
  55. // executed by the application.
  56. if (is_string($action))
  57. {
  58. static::$routes[$uri]['uses'] = $action;
  59. }
  60. // If the action is not a string, we can just simply cast it as an
  61. // array, then we will add all of the URIs to the action array as
  62. // the "handes" clause so we can easily check which URIs are
  63. // handled by the route instance.
  64. else
  65. {
  66. if ($action instanceof Closure) $action = array($action);
  67. static::$routes[$uri] = (array) $action;
  68. }
  69. static::$routes[$uri]['handles'] = (array) $route;
  70. }
  71. }
  72. /**
  73. * Find a route by the route's assigned name.
  74. *
  75. * @param string $name
  76. * @return array
  77. */
  78. public static function find($name)
  79. {
  80. if (isset(static::$names[$name])) return static::$names[$name];
  81. // If no route names have been found at all, we will assume no reverse
  82. // routing has been done, and we will load the routes file for all of
  83. // the bundle that are installed for the application.
  84. if (count(static::$names) == 0)
  85. {
  86. foreach (Bundle::names() as $bundle)
  87. {
  88. Bundle::routes($bundle);
  89. }
  90. }
  91. // To find a named route, we will iterate through every route defined
  92. // for the application. We will cache the routes by name so we can
  93. // load them very quickly if we need to find them a second time.
  94. foreach (static::$routes as $key => $value)
  95. {
  96. if (isset($value['name']) and $value['name'] == $name)
  97. {
  98. return static::$names[$name] = array($key => $value);
  99. }
  100. }
  101. }
  102. /**
  103. * Search the routes for the route matching a method and URI.
  104. *
  105. * @param string $method
  106. * @param string $uri
  107. * @return Route
  108. */
  109. public static function route($method, $uri)
  110. {
  111. // First we will make sure the bundle that handles the given URI has
  112. // been started for the current request. Bundles may handle any URI
  113. // as long as it begins with the string in the "handles" item of
  114. // the bundle's registration array.
  115. Bundle::start($bundle = Bundle::handles($uri));
  116. // All route URIs begin with the request method and have a leading
  117. // slash before the URI. We'll put the request method and URI in
  118. // that format so we can easily check for literal matches.
  119. $destination = $method.' /'.trim($uri, '/');
  120. if (array_key_exists($destination, static::$routes))
  121. {
  122. return new Route($destination, static::$routes[$destination], array());
  123. }
  124. // If we can't find a literal match, we'll iterate through all of
  125. // the registered routes to find a matching route that uses some
  126. // regular expressions or wildcards.
  127. if ( ! is_null($route = static::match($destination)))
  128. {
  129. return $route;
  130. }
  131. // If the bundle handling the request is not the default bundle,
  132. // we want to remove the root "handles" string from the URI so
  133. // it will not interfere with searching for a controller.
  134. //
  135. // If we left it on the URI, the root controller for the bundle
  136. // would need to be nested in directories matching the clause.
  137. // This will not intefere with the Route::handles method
  138. // as the destination is used to set the route's URIs.
  139. if ($bundle !== DEFAULT_BUNDLE)
  140. {
  141. $uri = str_replace(Bundle::get($bundle)->handles, '', $uri);
  142. $uri = ltrim($uri, '/');
  143. }
  144. $segments = Str::segments($uri);
  145. return static::controller($bundle, $method, $destination, $segments);
  146. }
  147. /**
  148. * Iterate through every route to find a matching route.
  149. *
  150. * @param string $destination
  151. * @return Route
  152. */
  153. protected static function match($destination)
  154. {
  155. foreach (static::$routes as $route => $action)
  156. {
  157. // We only need to check routes with regular expressions since
  158. // all other routes would have been able to be caught by the
  159. // check for literal matches we just did.
  160. if (strpos($route, '(') !== false)
  161. {
  162. $pattern = '#^'.static::wildcards($route).'$#';
  163. // If we get a match, we'll return the route and slice off
  164. // the first parameter match, as preg_match sets the first
  165. // array item to the full-text match.
  166. if (preg_match($pattern, $destination, $parameters))
  167. {
  168. return new Route($route, $action, array_slice($parameters, 1));
  169. }
  170. }
  171. }
  172. }
  173. /**
  174. * Attempt to find a controller for the incoming request.
  175. *
  176. * @param string $bundle
  177. * @param string $method
  178. * @param string $destination
  179. * @param array $segments
  180. * @return Route
  181. */
  182. protected static function controller($bundle, $method, $destination, $segments)
  183. {
  184. if (count($segments) == 0)
  185. {
  186. $uri = '/';
  187. // If the bundle is not the default bundle for the application, we'll
  188. // set the root URI as the root URI registered with the bundle in the
  189. // bundle configuration file for the application. It's registered in
  190. // the bundle configuration using the "handles" clause.
  191. if ($bundle !== DEFAULT_BUNDLE)
  192. {
  193. $uri = '/'.Bundle::get($bundle)->handles;
  194. }
  195. // We'll generate a default "uses" clause for the route action that
  196. // points to the default controller and method for the bundle so
  197. // that the route will execute the default.
  198. $action = array('uses' => Bundle::prefix($bundle).'home@index');
  199. return new Route($method.' '.$uri, $action);
  200. }
  201. $directory = Bundle::path($bundle).'controllers/';
  202. if ( ! is_null($key = static::locate($segments, $directory)))
  203. {
  204. // First, we'll extract the controller name, then, since we need
  205. // to extract the method and parameters, we will remove the name
  206. // of the controller from the URI. Then we can shift the method
  207. // off of the array of segments. Any remaining segments are the
  208. // parameters for the method.
  209. $controller = implode('.', array_slice($segments, 0, $key));
  210. $segments = array_slice($segments, $key);
  211. $method = (count($segments) > 0) ? array_shift($segments) : 'index';
  212. // We need to grab the prefix to the bundle so we can prefix
  213. // the route identifier with it. This informs the controller
  214. // class out of which bundle the controller instance should
  215. // be resolved when it is needed by the application.
  216. $prefix = Bundle::prefix($bundle);
  217. $action = array('uses' => $prefix.$controller.'@'.$method);
  218. return new Route($destination, $action, $segments);
  219. }
  220. }
  221. /**
  222. * Locate the URI segment matching a controller name.
  223. *
  224. * @param string $directory
  225. * @param array $segments
  226. * @return int
  227. */
  228. protected static function locate($segments, $directory)
  229. {
  230. for ($i = count($segments) - 1; $i >= 0; $i--)
  231. {
  232. // To find the proper controller, we need to iterate backwards through
  233. // the URI segments and take the first file that matches. That file
  234. // should be the deepest possible controller matched by the URI.
  235. if (file_exists($directory.implode('/', $segments).EXT))
  236. {
  237. return $i + 1;
  238. }
  239. // If a controller did not exist for the segments, we will pop
  240. // the last segment off of the array so that on the next run
  241. // through the loop we'll check one folder up from the one
  242. // we checked on this iteration.
  243. array_pop($segments);
  244. }
  245. }
  246. /**
  247. * Translate route URI wildcards into regular expressions.
  248. *
  249. * @param string $key
  250. * @return string
  251. */
  252. protected static function wildcards($key)
  253. {
  254. list($search, $replace) = array_divide(static::$optional);
  255. // For optional parameters, first translate the wildcards to their
  256. // regex equivalent, sans the ")?" ending. We'll add the endings
  257. // back on after we know how many replacements we made.
  258. $key = str_replace($search, $replace, $key, $count);
  259. if ($count > 0)
  260. {
  261. $key .= str_repeat(')?', $count);
  262. }
  263. return strtr($key, static::$patterns);
  264. }
  265. }