router.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. <?php namespace Laravel\Routing;
  2. use Closure;
  3. use Laravel\Str;
  4. use Laravel\Bundle;
  5. use Laravel\Request;
  6. class Router {
  7. /**
  8. * The route names that have been matched.
  9. *
  10. * @var array
  11. */
  12. public static $names = array();
  13. /**
  14. * The actions that have been reverse routed.
  15. *
  16. * @var array
  17. */
  18. public static $uses = array();
  19. /**
  20. * All of the routes that have been registered.
  21. *
  22. * @var array
  23. */
  24. public static $routes = array();
  25. /**
  26. * All of the "fallback" routes that have been registered.
  27. *
  28. * @var array
  29. */
  30. public static $fallback = array();
  31. /**
  32. * The current attributes being shared by routes.
  33. */
  34. public static $group;
  35. /**
  36. * The "handes" clause for the bundle currently being routed.
  37. *
  38. * @var string
  39. */
  40. public static $bundle;
  41. /**
  42. * The number of URI segments allowed as method arguments.
  43. *
  44. * @var int
  45. */
  46. public static $segments = 5;
  47. /**
  48. * The wildcard patterns supported by the router.
  49. *
  50. * @var array
  51. */
  52. public static $patterns = array(
  53. '(:num)' => '([0-9]+)',
  54. '(:any)' => '([a-zA-Z0-9\.\-_%]+)',
  55. '(:all)' => '(.*)',
  56. );
  57. /**
  58. * The optional wildcard patterns supported by the router.
  59. *
  60. * @var array
  61. */
  62. public static $optional = array(
  63. '/(:num?)' => '(?:/([0-9]+)',
  64. '/(:any?)' => '(?:/([a-zA-Z0-9\.\-_%]+)',
  65. '/(:all?)' => '(?:/(.*)',
  66. );
  67. /**
  68. * An array of HTTP request methods.
  69. *
  70. * @var array
  71. */
  72. public static $methods = array('GET', 'POST', 'PUT', 'DELETE');
  73. /**
  74. * Register a HTTPS route with the router.
  75. *
  76. * @param string $method
  77. * @param string|array $route
  78. * @param mixed $action
  79. * @return void
  80. */
  81. public static function secure($method, $route, $action)
  82. {
  83. $action = static::action($action);
  84. $action['https'] = true;
  85. static::register($method, $route, $action);
  86. }
  87. /**
  88. * Register a group of routes that share attributes.
  89. *
  90. * @param array $attributes
  91. * @param Closure $callback
  92. * @return void
  93. */
  94. public static function group($attributes, Closure $callback)
  95. {
  96. // Route groups allow the developer to specify attributes for a group
  97. // of routes. To register them, we'll set a static property on the
  98. // router so that the register method will see them.
  99. static::$group = $attributes;
  100. call_user_func($callback);
  101. // Once the routes have been registered, we want to set the group to
  102. // null so the attributes will not be assigned to any of the routes
  103. // that are added after the group is declared.
  104. static::$group = null;
  105. }
  106. /**
  107. * Register a route with the router.
  108. *
  109. * <code>
  110. * // Register a route with the router
  111. * Router::register('GET' ,'/', function() {return 'Home!';});
  112. *
  113. * // Register a route that handles multiple URIs with the router
  114. * Router::register(array('GET', '/', 'GET /home'), function() {return 'Home!';});
  115. * </code>
  116. *
  117. * @param string $method
  118. * @param string|array $route
  119. * @param mixed $action
  120. * @return void
  121. */
  122. public static function register($method, $route, $action)
  123. {
  124. if (is_string($route)) $route = explode(', ', $route);
  125. foreach ((array) $route as $uri)
  126. {
  127. // If the URI begins with a splat, we'll call the universal method, which
  128. // will register a route for each of the request methods supported by
  129. // the router. This is just a notational short-cut.
  130. if ($method == '*')
  131. {
  132. foreach (static::$methods as $method)
  133. {
  134. static::register($method, $route, $action);
  135. }
  136. continue;
  137. }
  138. $uri = str_replace('(:bundle)', static::$bundle, $uri);
  139. // If the URI begins with a wildcard, we want to add this route to the
  140. // array of "fallback" routes. Fallback routes are always processed
  141. // last when parsing routes since they are very generic and could
  142. // overload bundle routes that are registered.
  143. if ($uri[0] == '(')
  144. {
  145. $routes =& static::$fallback;
  146. }
  147. else
  148. {
  149. $routes =& static::$routes;
  150. }
  151. // If the action is an array, we can simply add it to the array of
  152. // routes keyed by the URI. Otherwise, we will need to call into
  153. // the action method to get a valid action array.
  154. if (is_array($action))
  155. {
  156. $routes[$method][$uri] = $action;
  157. }
  158. else
  159. {
  160. $routes[$method][$uri] = static::action($action);
  161. }
  162. // If a group is being registered, we'll merge all of the group
  163. // options into the action, giving preference to the action
  164. // for options that are specified in both.
  165. if ( ! is_null(static::$group))
  166. {
  167. $routes[$method][$uri] += static::$group;
  168. }
  169. // If the HTTPS option is not set on the action, we'll use the
  170. // value given to the method. The secure method passes in the
  171. // HTTPS value in as a parameter short-cut.
  172. if ( ! isset($routes[$method][$uri]['https']))
  173. {
  174. $routes[$method][$uri]['https'] = false;
  175. }
  176. }
  177. }
  178. /**
  179. * Convert a route action to a valid action array.
  180. *
  181. * @param mixed $action
  182. * @return array
  183. */
  184. protected static function action($action)
  185. {
  186. // If the action is a string, it is a pointer to a controller, so we
  187. // need to add it to the action array as a "uses" clause, which will
  188. // indicate to the route to call the controller.
  189. if (is_string($action))
  190. {
  191. $action = array('uses' => $action);
  192. }
  193. // If the action is a Closure, we will manually put it in an array
  194. // to work around a bug in PHP 5.3.2 which causes Closures cast
  195. // as arrays to become null. We'll remove this.
  196. elseif ($action instanceof Closure)
  197. {
  198. $action = array($action);
  199. }
  200. return (array) $action;
  201. }
  202. /**
  203. * Register a secure controller with the router.
  204. *
  205. * @param string|array $controllers
  206. * @param string|array $defaults
  207. * @return void
  208. */
  209. public static function secure_controller($controllers, $defaults = 'index')
  210. {
  211. static::controller($controllers, $defaults, true);
  212. }
  213. /**
  214. * Register a controller with the router.
  215. *
  216. * @param string|array $controller
  217. * @param string|array $defaults
  218. * @param bool $https
  219. * @return void
  220. */
  221. public static function controller($controllers, $defaults = 'index', $https = false)
  222. {
  223. foreach ((array) $controllers as $identifier)
  224. {
  225. list($bundle, $controller) = Bundle::parse($identifier);
  226. // First we need to replace the dots with slashes in thte controller name
  227. // so that it is in directory format. The dots allow the developer to use
  228. // a cleaner syntax when specifying the controller. We will also grab the
  229. // root URI for the controller's bundle.
  230. $controller = str_replace('.', '/', $controller);
  231. $root = Bundle::option($bundle, 'handles');
  232. // If the controller is a "home" controller, we'll need to also build a
  233. // index method route for the controller. We'll remove "home" from the
  234. // route root and setup a route to point to the index method.
  235. if (ends_with($controller, 'home'))
  236. {
  237. static::root($identifier, $controller, $root);
  238. }
  239. // The number of method arguments allowed for a controller is set by a
  240. // "segments" constant on this class which allows for the developer to
  241. // increase or decrease the limit on method arguments.
  242. $wildcards = static::repeat('(:any?)', static::$segments);
  243. // Once we have the path and root URI we can build a simple route for
  244. // the controller that should handle a conventional controller route
  245. // setup of controller/method/segment/segment, etc.
  246. $pattern = trim("{$root}/{$controller}/{$wildcards}", '/');
  247. // Finally we can build the "uses" clause and the attributes for the
  248. // controller route and register it with the router with a wildcard
  249. // method so it is available on every request method.
  250. $uses = "{$identifier}@(:1)";
  251. $attributes = compact('uses', 'defaults', 'https');
  252. static::register('*', $pattern, $attributes);
  253. }
  254. }
  255. /**
  256. * Register a route for the root of a controller.
  257. *
  258. * @param string $identifier
  259. * @param string $controller
  260. * @param string $root
  261. * @return void
  262. */
  263. protected static function root($identifier, $controller, $root)
  264. {
  265. // First we need to strip "home" off of the controller name to create the
  266. // URI needed to match the controller's folder, which should match the
  267. // root URI we want to point to the index method.
  268. if ($controller !== 'home')
  269. {
  270. $home = dirname($controller);
  271. }
  272. else
  273. {
  274. $home = '';
  275. }
  276. // After we trim the "home" off of the controller name we'll build the
  277. // pattern needed to map to the controller and then register a route
  278. // to point the pattern to the controller's index method.
  279. $pattern = trim($root.'/'.$home, '/') ?: '/';
  280. $attributes = array('uses' => "{$identifier}@index");
  281. static::register('*', $pattern, $attributes);
  282. }
  283. /**
  284. * Find a route by the route's assigned name.
  285. *
  286. * @param string $name
  287. * @return array
  288. */
  289. public static function find($name)
  290. {
  291. if (isset(static::$names[$name])) return static::$names[$name];
  292. // If no route names have been found at all, we will assume no reverse
  293. // routing has been done, and we will load the routes file for all of
  294. // the bundles that are installed for the application.
  295. if (count(static::$names) == 0)
  296. {
  297. foreach (Bundle::names() as $bundle)
  298. {
  299. Bundle::routes($bundle);
  300. }
  301. }
  302. // To find a named route, we will iterate through every route defined
  303. // for the application. We will cache the routes by name so we can
  304. // load them very quickly the next time.
  305. foreach (static::all() as $key => $value)
  306. {
  307. if (array_get($value, 'name') === $name)
  308. {
  309. return static::$names[$name] = array($key => $value);
  310. }
  311. }
  312. }
  313. /**
  314. * Find the route that uses the given action.
  315. *
  316. * @param string $action
  317. * @return array
  318. */
  319. public static function uses($action)
  320. {
  321. // If the action has already been reverse routed before, we'll just
  322. // grab the previously found route to save time. They are cached
  323. // in a static array on the class.
  324. if (isset(static::$uses[$action]))
  325. {
  326. return static::$uses[$action];
  327. }
  328. Bundle::routes(Bundle::name($action));
  329. // To find the route, we'll simply spin through the routes looking
  330. // for a route with a "uses" key matching the action, and if we
  331. // find one we cache and return it.
  332. foreach (static::all() as $uri => $route)
  333. {
  334. if (array_get($route, 'uses') == $action)
  335. {
  336. return static::$uses[$action] = array($uri => $route);
  337. }
  338. }
  339. }
  340. /**
  341. * Search the routes for the route matching a method and URI.
  342. *
  343. * @param string $method
  344. * @param string $uri
  345. * @return Route
  346. */
  347. public static function route($method, $uri)
  348. {
  349. Bundle::start($bundle = Bundle::handles($uri));
  350. // Of course literal route matches are the quickest to find, so we will
  351. // check for those first. If the destination key exists in teh routes
  352. // array we can just return that route now.
  353. if (array_key_exists($uri, static::$routes[$method]))
  354. {
  355. $action = static::$routes[$method][$uri];
  356. return new Route($method, $uri, $action);
  357. }
  358. // If we can't find a literal match we'll iterate through all of the
  359. // registered routes to find a matching route based on the route's
  360. // regular expressions and wildcards.
  361. if ( ! is_null($route = static::match($method, $uri)))
  362. {
  363. return $route;
  364. }
  365. }
  366. /**
  367. * Iterate through every route to find a matching route.
  368. *
  369. * @param string $method
  370. * @param string $uri
  371. * @return Route
  372. */
  373. protected static function match($method, $uri)
  374. {
  375. foreach (static::routes($method) as $route => $action)
  376. {
  377. // We only need to check routes with regular expression since all other
  378. // would have been able to be matched by the search for literal matches
  379. // we just did before we started searching.
  380. if (str_contains($route, '('))
  381. {
  382. $pattern = '#^'.static::wildcards($route).'$#';
  383. // If we get a match we'll return the route and slice off the first
  384. // parameter match, as preg_match sets the first array item to the
  385. // full-text match of the pattern.
  386. if (preg_match($pattern, $uri, $parameters))
  387. {
  388. return new Route($method, $route, $action, array_slice($parameters, 1));
  389. }
  390. }
  391. }
  392. }
  393. /**
  394. * Translate route URI wildcards into regular expressions.
  395. *
  396. * @param string $key
  397. * @return string
  398. */
  399. protected static function wildcards($key)
  400. {
  401. list($search, $replace) = array_divide(static::$optional);
  402. // For optional parameters, first translate the wildcards to their
  403. // regex equivalent, sans the ")?" ending. We'll add the endings
  404. // back on when we know the replacement count.
  405. $key = str_replace($search, $replace, $key, $count);
  406. if ($count > 0)
  407. {
  408. $key .= str_repeat(')?', $count);
  409. }
  410. return strtr($key, static::$patterns);
  411. }
  412. /**
  413. * Get all of the routes across all request methods.
  414. *
  415. * @return array
  416. */
  417. public static function all()
  418. {
  419. $all = array();
  420. // To get all the routes, we'll just loop through each request
  421. // method supported by the router and merge in each of the
  422. // arrays into the main array of routes.
  423. foreach (static::$methods as $method)
  424. {
  425. $all = array_merge($all, static::routes($method));
  426. }
  427. return $all;
  428. }
  429. /**
  430. * Get all of the registered routes, with fallbacks at the end.
  431. *
  432. * @param string $method
  433. * @return array
  434. */
  435. public static function routes($method = null)
  436. {
  437. $routes = array_get(static::$routes, $method, array());
  438. return array_merge($routes, array_get(static::$fallback, $method, array()));
  439. }
  440. /**
  441. * Get all of the wildcard patterns
  442. *
  443. * @return array
  444. */
  445. public static function patterns()
  446. {
  447. return array_merge(static::$patterns, static::$optional);
  448. }
  449. /**
  450. * Get a string repeating a URI pattern any number of times.
  451. *
  452. * @param string $pattern
  453. * @param int $times
  454. * @return string
  455. */
  456. protected static function repeat($pattern, $times)
  457. {
  458. return implode('/', array_fill(0, $times, $pattern));
  459. }
  460. }