router.php 15 KB

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