router.php 15 KB

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