Router.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. <?php
  2. /**
  3. * Slim - a micro PHP 5 framework
  4. *
  5. * @author Josh Lockhart <[email protected]>
  6. * @copyright 2011 Josh Lockhart
  7. * @link http://www.slimframework.com
  8. * @license http://www.slimframework.com/license
  9. * @version 2.2.0
  10. * @package Slim
  11. *
  12. * MIT LICENSE
  13. *
  14. * Permission is hereby granted, free of charge, to any person obtaining
  15. * a copy of this software and associated documentation files (the
  16. * "Software"), to deal in the Software without restriction, including
  17. * without limitation the rights to use, copy, modify, merge, publish,
  18. * distribute, sublicense, and/or sell copies of the Software, and to
  19. * permit persons to whom the Software is furnished to do so, subject to
  20. * the following conditions:
  21. *
  22. * The above copyright notice and this permission notice shall be
  23. * included in all copies or substantial portions of the Software.
  24. *
  25. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. */
  33. namespace Slim;
  34. /**
  35. * Router
  36. *
  37. * This class organizes, iterates, and dispatches \Slim\Route objects.
  38. *
  39. * @package Slim
  40. * @author Josh Lockhart
  41. * @since 1.0.0
  42. */
  43. class Router
  44. {
  45. /**
  46. * @var Route The current route (most recently dispatched)
  47. */
  48. protected $currentRoute;
  49. /**
  50. * @var array Lookup hash of all route objects
  51. */
  52. protected $routes;
  53. /**
  54. * @var array Lookup hash of named route objects, keyed by route name (lazy-loaded)
  55. */
  56. protected $namedRoutes;
  57. /**
  58. * @var array Array of route objects that match the request URI (lazy-loaded)
  59. */
  60. protected $matchedRoutes;
  61. /**
  62. * Constructor
  63. */
  64. public function __construct()
  65. {
  66. $this->routes = array();
  67. }
  68. /**
  69. * Get Current Route object or the first matched one if matching has been performed
  70. * @return \Slim\Route|null
  71. */
  72. public function getCurrentRoute()
  73. {
  74. if ($this->currentRoute !== null) {
  75. return $this->currentRoute;
  76. }
  77. if (is_array($this->matchedRoutes) && count($this->matchedRoutes) > 0) {
  78. return $this->matchedRoutes[0];
  79. }
  80. return null;
  81. }
  82. /**
  83. * Return route objects that match the given HTTP method and URI
  84. * @param string $httpMethod The HTTP method to match against
  85. * @param string $resourceUri The resource URI to match against
  86. * @param bool $reload Should matching routes be re-parsed?
  87. * @return array[\Slim\Route]
  88. */
  89. public function getMatchedRoutes($httpMethod, $resourceUri, $reload = false)
  90. {
  91. if ($reload || is_null($this->matchedRoutes)) {
  92. $this->matchedRoutes = array();
  93. foreach ($this->routes as $route) {
  94. if (!$route->supportsHttpMethod($httpMethod)) {
  95. continue;
  96. }
  97. if ($route->matches($resourceUri)) {
  98. $this->matchedRoutes[] = $route;
  99. }
  100. }
  101. }
  102. return $this->matchedRoutes;
  103. }
  104. /**
  105. * Map a route object to a callback function
  106. * @param string $pattern The URL pattern (ie. "/books/:id")
  107. * @param mixed $callable Anything that returns TRUE for is_callable()
  108. * @return \Slim\Route
  109. */
  110. public function map($pattern, $callable)
  111. {
  112. $route = new \Slim\Route($pattern, $callable);
  113. $this->routes[] = $route;
  114. return $route;
  115. }
  116. /**
  117. * Get URL for named route
  118. * @param string $name The name of the route
  119. * @param array Associative array of URL parameter names and replacement values
  120. * @throws RuntimeException If named route not found
  121. * @return string The URL for the given route populated with provided replacement values
  122. */
  123. public function urlFor($name, $params = array())
  124. {
  125. if (!$this->hasNamedRoute($name)) {
  126. throw new \RuntimeException('Named route not found for name: ' . $name);
  127. }
  128. $search = array();
  129. foreach (array_keys($params) as $key) {
  130. $search[] = '#:' . $key . '\+?(?!\w)#';
  131. }
  132. $pattern = preg_replace($search, $params, $this->getNamedRoute($name)->getPattern());
  133. //Remove remnants of unpopulated, trailing optional pattern segments
  134. return preg_replace('#\(/?:.+\)|\(|\)#', '', $pattern);
  135. }
  136. /**
  137. * Dispatch route
  138. *
  139. * This method invokes the route object's callable. If middleware is
  140. * registered for the route, each callable middleware is invoked in
  141. * the order specified.
  142. *
  143. * @param \Slim\Route $route The route object
  144. * @return bool Was route callable invoked successfully?
  145. */
  146. public function dispatch(\Slim\Route $route)
  147. {
  148. $this->currentRoute = $route;
  149. //Invoke middleware
  150. foreach ($route->getMiddleware() as $mw) {
  151. call_user_func_array($mw, array($route));
  152. }
  153. //Invoke callable
  154. call_user_func_array($route->getCallable(), array_values($route->getParams()));
  155. return true;
  156. }
  157. /**
  158. * Add named route
  159. * @param string $name The route name
  160. * @param \Slim\Route $route The route object
  161. * @throws \RuntimeException If a named route already exists with the same name
  162. */
  163. public function addNamedRoute($name, \Slim\Route $route)
  164. {
  165. if ($this->hasNamedRoute($name)) {
  166. throw new \RuntimeException('Named route already exists with name: ' . $name);
  167. }
  168. $this->namedRoutes[(string) $name] = $route;
  169. }
  170. /**
  171. * Has named route
  172. * @param string $name The route name
  173. * @return bool
  174. */
  175. public function hasNamedRoute($name)
  176. {
  177. $this->getNamedRoutes();
  178. return isset($this->namedRoutes[(string) $name]);
  179. }
  180. /**
  181. * Get named route
  182. * @param string $name
  183. * @return \Slim\Route|null
  184. */
  185. public function getNamedRoute($name)
  186. {
  187. $this->getNamedRoutes();
  188. if ($this->hasNamedRoute($name)) {
  189. return $this->namedRoutes[(string) $name];
  190. } else {
  191. return null;
  192. }
  193. }
  194. /**
  195. * Get named routes
  196. * @return \ArrayIterator
  197. */
  198. public function getNamedRoutes()
  199. {
  200. if (is_null($this->namedRoutes)) {
  201. $this->namedRoutes = array();
  202. foreach ($this->routes as $route) {
  203. if ($route->getName() !== null) {
  204. $this->addNamedRoute($route->getName(), $route);
  205. }
  206. }
  207. }
  208. return new \ArrayIterator($this->namedRoutes);
  209. }
  210. }