router.php 15 KB

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