Route.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. <?php
  2. /**
  3. * Lithium: the most rad php framework
  4. *
  5. * @copyright Copyright 2013, Union of RAD (http://union-of-rad.org)
  6. * @license http://opensource.org/licenses/bsd-license.php The BSD License
  7. */
  8. namespace lithium\net\http;
  9. /**
  10. * The `Route` class represents a single URL pattern which is matched against incoming requests, in
  11. * order to determine the correct controller and action that an HTTP request should be dispatched
  12. * to.
  13. *
  14. * Typically, `Route` objects are created and handled through the `lithium\net\http\Router` class,
  15. * as follows:
  16. *
  17. * {{{// This instantiates a Route object behind the scenes, and adds it to Router's collection:
  18. * Router::connect("/{:controller}/{:action}");
  19. *
  20. * // This matches a set of parameters against all Route objects contained in Router, and if a match
  21. * // is found, returns a string URL with parameters inserted into the URL pattern:
  22. * Router::match(array("controller" => "users", "action" => "login")); // returns "/users/login"
  23. * }}}
  24. *
  25. * For more advanced routing, however, you can directly instantiate a `Route` object, a subclass,
  26. * or any class that implements `parse()` and `match()` (see the documentation for each individual
  27. * method) and configure it manually -- if, for example, you want the route to match different
  28. * incoming URLs than it generates.
  29. *
  30. * {{{$route = new Route(array(
  31. * 'template' => '/users/{:user}',
  32. * 'pattern' => '@^/u(?:sers)?(?:/(?P<user>[^\/]+))$@',
  33. * 'params' => array('controller' => 'users', 'action' => 'index'),
  34. * 'match' => array('controller' => 'users', 'action' => 'index'),
  35. * 'defaults' => array('controller' => 'users'),
  36. * 'keys' => array('user' => 'user'),
  37. * 'options' => array('compile' => false, 'wrap' => false)
  38. * ));
  39. * Router::connect($route); // this will match '/users/<username>' or '/u/<username>'.
  40. * }}}
  41. *
  42. * For additional information on the `'options'` constructor key, see
  43. * `lithium\net\http\Route::compile()`. To learn more about Lithium's routing system, see
  44. * `lithium\net\http\Router`.
  45. *
  46. * @see lithium\net\http\Route::compile()
  47. * @see lithium\net\http\Router
  48. */
  49. class Route extends \lithium\core\Object {
  50. /**
  51. * The URL template string that the route matches.
  52. *
  53. * This string can contain fixed elements, i.e. `"/admin"`, capture elements,
  54. * i.e. `"/{:controller}"`, capture elements optionally paired with regular expressions or
  55. * named regular expression patterns, i.e. `"/{:id:\d+}"` or `"/{:id:ID}"`, the special wildcard
  56. * capture, i.e. `"{:args}"`, or any combination thereof, i.e.
  57. * `"/admin/{:controller}/{:id:\d+}/{:args}"`.
  58. *
  59. * @var string
  60. */
  61. protected $_template = '';
  62. /**
  63. * The regular expression used to match URLs.
  64. *
  65. * This regular expression is typically 'compiled' down from the higher-level syntax used in
  66. * `$_template`, but can be set manually with compilation turned off in the constructor for
  67. * extra control or if you are using pre-compiled `Route` objects.
  68. *
  69. * @var string
  70. * @see lithium\net\http\Route::$_template
  71. * @see lithium\net\http\Route::__construct()
  72. */
  73. protected $_pattern = '';
  74. /**
  75. * An array of route parameter names (i.e. {:foo}) that appear in the URL template.
  76. *
  77. * @var array
  78. * @see lithium\net\http\Route::$_template
  79. */
  80. protected $_keys = array();
  81. /**
  82. * An array of key/value pairs representing the parameters of the route. For keys which match
  83. * parameters present in the route template, the corresponding values match the default values
  84. * of those parameters. Specifying a default value for a template parameter makes that
  85. * parameter optional. Any other pairs specified must match exactly when doing a reverse lookup
  86. * in order for the route to match.
  87. *
  88. * @var array
  89. */
  90. protected $_params = array();
  91. /**
  92. * The array of values that appear in the second parameter of `Router::connect()`, which are
  93. * **not** present in the URL template. When matching a route, these parameters must appear
  94. * **exactly** as specified here.
  95. *
  96. * @var array
  97. */
  98. protected $_match = array();
  99. /**
  100. * An array of metadata parameters which must be present in the request in order for the route
  101. * to match.
  102. *
  103. * @var array
  104. */
  105. protected $_meta = array();
  106. /**
  107. * The default values for the keys present in the URL template.
  108. *
  109. * @var array
  110. * @see lithium\net\http\Route::$_template
  111. * @see lithium\net\http\Route::$_keys
  112. */
  113. protected $_defaults = array();
  114. /**
  115. * An array of regular expression patterns used in route matching.
  116. *
  117. * @var array
  118. */
  119. protected $_subPatterns = array();
  120. /**
  121. * An array of parameter names which will persist by default when generating URLs. By default,
  122. * the `'controller'` parameter is set to persist, which means that the controller name matched
  123. * for a given request will be used to generate all URLs for that request, unless the
  124. * `'controller'` parameter is specified in that URL with another value.
  125. *
  126. * @var array
  127. */
  128. protected $_persist = array();
  129. /**
  130. * Contains a function which will be executed if this route is matched. The function takes the
  131. * instance of the associated `Request` object, and the array of matched route parameters, and
  132. * must return either the parameters array (which may be modified by the handler) or a
  133. * `Response` object, in which case the response will be returned directly. This may be used to
  134. * handle redirects, or simple API services.
  135. *
  136. * @var object
  137. */
  138. protected $_handler = null;
  139. /**
  140. * Array of closures used to format route parameters when compiling URLs.
  141. *
  142. * @see lithium\net\http\Router::formatters()
  143. * @var array
  144. */
  145. protected $_formatters = array();
  146. /**
  147. * Auto configuration properties. Also used as the list of properties to return when exporting
  148. * this `Route` object to an array.
  149. *
  150. * @see lithium\net\http\Route::export()
  151. * @var array
  152. */
  153. protected $_autoConfig = array(
  154. 'template', 'pattern', 'params', 'match', 'meta',
  155. 'keys', 'defaults', 'subPatterns', 'persist', 'handler'
  156. );
  157. public function __construct(array $config = array()) {
  158. $defaults = array(
  159. 'params' => array(),
  160. 'template' => '/',
  161. 'pattern' => '',
  162. 'match' => array(),
  163. 'meta' => array(),
  164. 'defaults' => array(),
  165. 'keys' => array(),
  166. 'persist' => array(),
  167. 'handler' => null,
  168. 'continue' => false,
  169. 'formatters' => array(),
  170. 'unicode' => true
  171. );
  172. parent::__construct($config + $defaults);
  173. }
  174. protected function _init() {
  175. parent::_init();
  176. if (!$this->_config['continue'] && !preg_match('@{:action:.*?}@', $this->_template)) {
  177. $this->_params += array('action' => 'index');
  178. }
  179. if (!$this->_config['pattern']) {
  180. $this->compile();
  181. }
  182. if ($isKey = isset($this->_keys['controller']) || isset($this->_params['controller'])) {
  183. $this->_persist = $this->_persist ?: array('controller');
  184. }
  185. }
  186. /**
  187. * Attempts to parse a request object and determine its execution details.
  188. *
  189. * @param object $request A request object, usually an instance of `lithium\net\http\Request`,
  190. * containing the details of the request to be routed.
  191. * @param array $options Used to determine the operation of the method, and override certain
  192. * values in the `Request` object:
  193. * - `'url'` _string_: If present, will be used to match in place of the `$url`
  194. * property of `$request`.
  195. * @return mixed If this route matches `$request`, returns an array of the execution details
  196. * contained in the route, otherwise returns false.
  197. */
  198. public function parse($request, array $options = array()) {
  199. $defaults = array('url' => $request->url);
  200. $options += $defaults;
  201. $url = '/' . trim($options['url'], '/');
  202. $pattern = $this->_pattern;
  203. if (!preg_match($pattern, $url, $match)) {
  204. return false;
  205. }
  206. foreach ($this->_meta as $key => $compare) {
  207. $value = $request->get($key);
  208. if (!($compare == $value || (is_array($compare) && in_array($value, $compare)))) {
  209. return false;
  210. }
  211. }
  212. if (isset($match['args'])) {
  213. $match['args'] = explode('/', $match['args']);
  214. }
  215. $result = array_filter(array_intersect_key($match, $this->_keys));
  216. if (isset($this->_keys['args'])) {
  217. $result += array('args' => array());
  218. }
  219. $result += $this->_params + $this->_defaults;
  220. $request->params = $result + (array) $request->params;
  221. $request->persist = array_unique(array_merge($request->persist, $this->_persist));
  222. if ($this->_handler) {
  223. $handler = $this->_handler;
  224. return $handler($request);
  225. }
  226. return $request;
  227. }
  228. /**
  229. * Matches a set of parameters against the route, and returns a URL string if the route matches
  230. * the parameters, or false if it does not match.
  231. *
  232. * @param array $options
  233. * @param string $context
  234. * @return mixed
  235. */
  236. public function match(array $options = array(), $context = null) {
  237. $defaults = array('action' => 'index');
  238. $query = null;
  239. if (!$this->_config['continue']) {
  240. $options += $defaults;
  241. if (isset($options['?'])) {
  242. $query = $options['?'];
  243. $query = '?' . (is_array($query) ? http_build_query($query) : $query);
  244. unset($options['?']);
  245. }
  246. }
  247. if (!$options = $this->_matchKeys($options)) {
  248. return false;
  249. }
  250. foreach ($this->_subPatterns as $key => $pattern) {
  251. if (isset($options[$key]) && !preg_match("/^{$pattern}$/", $options[$key])) {
  252. return false;
  253. }
  254. }
  255. $defaults = $this->_defaults + $defaults;
  256. if ($this->_config['continue']) {
  257. return $this->_write(array('args' => '{:args}') + $options, $this->_defaults);
  258. }
  259. return $this->_write($options, $defaults + array('args' => '')) . $query;
  260. }
  261. /**
  262. * Returns a boolean value indicating whether this is a continuation route. If `true`, this
  263. * route will allow incoming requests to "fall through" to other routes, aggregating parameters
  264. * for both this route and any subsequent routes.
  265. *
  266. * @return boolean Returns the value of `$_config['continue']`.
  267. */
  268. public function canContinue() {
  269. return $this->_config['continue'];
  270. }
  271. /**
  272. * A helper method used by `match()` to verify that options required to match this route are
  273. * present in a URL array.
  274. *
  275. * @see lithium\net\http\Route::match()
  276. * @param array $options An array of URL parameters.
  277. * @return mixed On success, returns an updated array of options, merged with defaults. On
  278. * failure, returns `false`.
  279. */
  280. protected function _matchKeys($options) {
  281. $args = array('args' => 'args');
  282. if (array_intersect_key($options, $this->_match) != $this->_match) {
  283. return false;
  284. }
  285. if ($this->_config['continue']) {
  286. if (array_intersect_key($this->_keys, $options + $args) != $this->_keys) {
  287. return false;
  288. }
  289. } else {
  290. if (array_diff_key(array_diff_key($options, $this->_match), $this->_keys) !== array()) {
  291. return false;
  292. }
  293. }
  294. $options += $this->_defaults;
  295. $base = $this->_keys + $args;
  296. $match = array_intersect_key($this->_keys, $options) + $args;
  297. sort($base);
  298. sort($match);
  299. if ($base !== $match) {
  300. return false;
  301. }
  302. return $options;
  303. }
  304. /**
  305. * Writes a set of URL options to this route's template string.
  306. *
  307. * @param array $options The options to write to this route, with defaults pre-merged.
  308. * @param array $defaults The default template options for this route (contains hard-coded
  309. * default values).
  310. * @return string Returns the route template string with option values inserted.
  311. */
  312. protected function _write($options, $defaults) {
  313. $template = $this->_template;
  314. $trimmed = true;
  315. $options += array('args' => '');
  316. foreach (array_reverse($this->_keys, true) as $key) {
  317. $value =& $options[$key];
  318. $pattern = isset($this->_subPatterns[$key]) ? ":{$this->_subPatterns[$key]}" : '';
  319. $rpl = "{:{$key}{$pattern}}";
  320. $len = strlen($rpl) * -1;
  321. if ($trimmed && isset($defaults[$key]) && $value == $defaults[$key]) {
  322. if (substr($template, $len) == $rpl) {
  323. $template = rtrim(substr($template, 0, $len), '/');
  324. continue;
  325. }
  326. }
  327. if (isset($this->_config['formatters'][$key])) {
  328. $value = $this->_config['formatters'][$key]($value);
  329. }
  330. if ($value === null) {
  331. $template = str_replace("/{$rpl}", '', $template);
  332. continue;
  333. }
  334. if ($key !== 'args') {
  335. $trimmed = false;
  336. }
  337. $template = str_replace($rpl, $value, $template);
  338. }
  339. return $template ?: '/';
  340. }
  341. /**
  342. * Exports the properties that make up the route to an array, for debugging, caching or
  343. * introspection purposes.
  344. *
  345. * @return array An array containing the properties of the route object, such as URL templates
  346. * and parameter lists.
  347. */
  348. public function export() {
  349. $result = array();
  350. foreach ($this->_autoConfig as $key) {
  351. if ($key === 'formatters') {
  352. continue;
  353. }
  354. $result[$key] = $this->{'_' . $key};
  355. }
  356. return $result;
  357. }
  358. /**
  359. * Compiles URL templates into regular expression patterns for matching against request URLs,
  360. * and extracts template parameters into match-parameter arrays.
  361. *
  362. * @return void
  363. */
  364. public function compile() {
  365. $this->_match = $this->_params;
  366. foreach ($this->_params as $key => $value) {
  367. if (!strpos($key, ':')) {
  368. continue;
  369. }
  370. unset($this->_params[$key]);
  371. $this->_meta[$key] = $value;
  372. }
  373. if ($this->_template === '/' || $this->_template === '') {
  374. $this->_pattern = '@^/*$@';
  375. return;
  376. }
  377. $this->_pattern = "@^{$this->_template}\$@";
  378. $match = '@([/.])?\{:([^:}]+):?((?:[^{]+?(?:\{[0-9,]+\})?)*?)\}@S';
  379. if ($this->_config['unicode']) {
  380. $this->_pattern .= 'u';
  381. }
  382. preg_match_all($match, $this->_pattern, $m);
  383. if (!$tokens = $m[0]) {
  384. return;
  385. }
  386. $slashes = $m[1];
  387. $params = $m[2];
  388. $regexs = $m[3];
  389. unset($m);
  390. $this->_keys = array();
  391. foreach ($params as $i => $param) {
  392. $this->_keys[$param] = $param;
  393. $this->_pattern = $this->_regex($regexs[$i], $param, $tokens[$i], $slashes[$i]);
  394. }
  395. $this->_defaults = array_intersect_key($this->_params, $this->_keys);
  396. $this->_match = array_diff_key($this->_params, $this->_defaults);
  397. }
  398. /**
  399. * Generates a sub-expression capture group for a route regex, using an optional user-supplied
  400. * matching pattern.
  401. *
  402. * @param string $regex An optional user-supplied match pattern. If a route is defined like
  403. * `"/{:id:\d+}"`, then the value will be `"\d+"`.
  404. * @param string $param The parameter name which the capture group is assigned to, i.e.
  405. * `'controller'`, `'id'` or `'args'`.
  406. * @param string $token The full token representing a matched element in a route template, i.e.
  407. * `'/{:action}'`, `'/{:path:js|css}'`, or `'.{:type}'`.
  408. * @param string $prefix The prefix character that separates the parameter from the other
  409. * elements of the route. Usually `'.'` or `'/'`.
  410. * @return string Returns the full route template, with the value of `$token` replaced with a
  411. * generated regex capture group.
  412. */
  413. protected function _regex($regex, $param, $token, $prefix) {
  414. if ($regex) {
  415. $this->_subPatterns[$param] = $regex;
  416. } elseif ($param == 'args') {
  417. $regex = '.*';
  418. } else {
  419. $regex = '[^\/]+';
  420. }
  421. $req = $param === 'args' || array_key_exists($param, $this->_params) ? '?' : '';
  422. if ($prefix === '/') {
  423. $pattern = "(?:/(?P<{$param}>{$regex}){$req}){$req}";
  424. } elseif ($prefix === '.') {
  425. $pattern = "\\.(?P<{$param}>{$regex}){$req}";
  426. } else {
  427. $pattern = "(?P<{$param}>{$regex}){$req}";
  428. }
  429. return str_replace($token, $pattern, $this->_pattern);
  430. }
  431. }
  432. ?>