router.php 15 KB

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