router.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. <?php namespace Laravel\Routing;
  2. use Laravel\Request;
  3. class Router {
  4. /**
  5. * The route loader instance.
  6. *
  7. * @var Loader
  8. */
  9. public $loader;
  10. /**
  11. * The named routes that have been found so far.
  12. *
  13. * @var array
  14. */
  15. protected $names = array();
  16. /**
  17. * The path the application controllers.
  18. *
  19. * @var string
  20. */
  21. protected $controllers;
  22. /**
  23. * Create a new router for a request method and URI.
  24. *
  25. * @param Loader $loader
  26. * @param string $controllers
  27. * @return void
  28. */
  29. public function __construct(Loader $loader, $controllers)
  30. {
  31. $this->loader = $loader;
  32. $this->controllers = $controllers;
  33. }
  34. /**
  35. * Find a route by name.
  36. *
  37. * The returned array will be identical the array defined in the routes.php file.
  38. *
  39. * @param string $name
  40. * @return array
  41. */
  42. public function find($name)
  43. {
  44. // First we will check the cache of route names. If we have already found the given route,
  45. // we will simply return that route from the cache to improve performance.
  46. if (array_key_exists($name, $this->names)) return $this->names[$name];
  47. // Spin through every route defined for the application searching for a route that has
  48. // a name matching the name passed to the method. If the route is found, it will be
  49. // cached in the array of named routes and returned.
  50. foreach ($this->loader->everything() as $key => $value)
  51. {
  52. if (is_array($value) and isset($value['name']) and $value['name'] === $name)
  53. {
  54. return $this->names[$name] = array($key => $value);
  55. }
  56. }
  57. }
  58. /**
  59. * Search the routes for the route matching a request method and URI.
  60. *
  61. * @param Request $request
  62. * @param string $method
  63. * @param string $uri
  64. * @return Route
  65. */
  66. public function route(Request $request, $method, $uri)
  67. {
  68. $routes = $this->loader->load($uri);
  69. // Put the request method and URI in route form. Routes begin with
  70. // the request method and a forward slash.
  71. $destination = $method.' /'.trim($uri, '/');
  72. // Check for a literal route match first. If we find one, there is
  73. // no need to spin through all of the routes.
  74. if (isset($routes[$destination]))
  75. {
  76. return $request->route = new Route($destination, $routes[$destination], array());
  77. }
  78. foreach ($routes as $keys => $callback)
  79. {
  80. // Only check routes that have multiple URIs or wildcards.
  81. // Other routes would have been caught by the check for literal matches.
  82. if (strpos($keys, '(') !== false or strpos($keys, ',') !== false )
  83. {
  84. foreach (explode(', ', $keys) as $key)
  85. {
  86. // Append the provided formats to the route as an optional regular expression.
  87. if ( ! is_null($formats = $this->provides($callback))) $key .= '(\.('.implode('|', $formats).'))?';
  88. if (preg_match('#^'.$this->translate_wildcards($key).'$#', $destination))
  89. {
  90. return $request->route = new Route($keys, $callback, $this->parameters($destination, $key));
  91. }
  92. }
  93. }
  94. }
  95. return $request->route = $this->route_to_controller($method, $uri, $destination);
  96. }
  97. /**
  98. * Attempt to find a controller for the incoming request.
  99. *
  100. * @param string $method
  101. * @param string $uri
  102. * @param string $destination
  103. * @return Route
  104. */
  105. protected function route_to_controller($method, $uri, $destination)
  106. {
  107. // If the request is to the root of the application, an ad-hoc route will be generated
  108. // to the home controller's "index" method, making it the default controller method.
  109. if ($uri === '/') return new Route($method.' /', 'home@index');
  110. $segments = explode('/', trim($uri, '/'));
  111. if ( ! is_null($key = $this->controller_key($segments)))
  112. {
  113. // Create the controller name for the current request. This controller
  114. // name will be returned by the anonymous route we will create. Instead
  115. // of using directory slashes, dots will be used to specify the controller
  116. // location with the controllers directory.
  117. $controller = implode('.', array_slice($segments, 0, $key));
  118. // Now that we have the controller path and name, we can slice the controller
  119. // section of the URI from the array of segments.
  120. $segments = array_slice($segments, $key);
  121. // Extract the controller method from the URI segments. If no more segments
  122. // are remaining after slicing off the controller, the "index" method will
  123. // be used as the default controller method.
  124. $method = (count($segments) > 0) ? array_shift($segments) : 'index';
  125. return new Route($destination, $controller.'@'.$method, $segments);
  126. }
  127. }
  128. /**
  129. * Search the controllers for the application and determine if an applicable
  130. * controller exists for the current request.
  131. *
  132. * If a controller is found, the array key for the controller name in the URI
  133. * segments will be returned by the method, otherwise NULL will be returned.
  134. * The deepest possible matching controller will be considered the controller
  135. * that should handle the request.
  136. *
  137. * @param array $segments
  138. * @return int
  139. */
  140. protected function controller_key($segments)
  141. {
  142. foreach (array_reverse($segments, true) as $key => $value)
  143. {
  144. if (file_exists($path = $this->controllers.implode('/', array_slice($segments, 0, $key + 1)).EXT))
  145. {
  146. return $key + 1;
  147. }
  148. }
  149. }
  150. /**
  151. * Get the request formats for which the route provides responses.
  152. *
  153. * @param mixed $callback
  154. * @return array
  155. */
  156. protected function provides($callback)
  157. {
  158. return (is_array($callback) and isset($callback['provides'])) ? explode(', ', $callback['provides']) : null;
  159. }
  160. /**
  161. * Translate route URI wildcards into actual regular expressions.
  162. *
  163. * @param string $key
  164. * @return string
  165. */
  166. protected function translate_wildcards($key)
  167. {
  168. $replacements = 0;
  169. // For optional parameters, first translate the wildcards to their
  170. // regex equivalent, sans the ")?" ending. We will add the endings
  171. // back on after we know how many replacements we made.
  172. $key = str_replace(array('/(:num?)', '/(:any?)'), array('(?:/([0-9]+)', '(?:/([a-zA-Z0-9\.\-_]+)'), $key, $replacements);
  173. $key .= ($replacements > 0) ? str_repeat(')?', $replacements) : '';
  174. return str_replace(array(':num', ':any'), array('[0-9]+', '[a-zA-Z0-9\.\-_]+'), $key);
  175. }
  176. /**
  177. * Extract the parameters from a URI based on a route URI.
  178. *
  179. * Any route segment wrapped in parentheses is considered a parameter.
  180. *
  181. * @param string $uri
  182. * @param string $route
  183. * @return array
  184. */
  185. protected function parameters($uri, $route)
  186. {
  187. return array_values(array_intersect_key(explode('/', $uri), preg_grep('/\(.+\)/', explode('/', $route))));
  188. }
  189. }