PageRenderTime 42ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Routing/Route/CakeRoute.php

https://bitbucket.org/LeThanhDat/firstdummyapp
PHP | 544 lines | 339 code | 50 blank | 155 comment | 86 complexity | d3d0741793aff8cfe1c2c76e87ce115a MD5 | raw file
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since CakePHP(tm) v 1.3
  13. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  14. */
  15. App::uses('Hash', 'Utility');
  16. /**
  17. * A single Route used by the Router to connect requests to
  18. * parameter maps.
  19. *
  20. * Not normally created as a standalone. Use Router::connect() to create
  21. * Routes for your application.
  22. *
  23. * @package Cake.Routing.Route
  24. */
  25. class CakeRoute {
  26. /**
  27. * An array of named segments in a Route.
  28. * `/:controller/:action/:id` has 3 key elements
  29. *
  30. * @var array
  31. */
  32. public $keys = array();
  33. /**
  34. * An array of additional parameters for the Route.
  35. *
  36. * @var array
  37. */
  38. public $options = array();
  39. /**
  40. * Default parameters for a Route
  41. *
  42. * @var array
  43. */
  44. public $defaults = array();
  45. /**
  46. * The routes template string.
  47. *
  48. * @var string
  49. */
  50. public $template = null;
  51. /**
  52. * Is this route a greedy route? Greedy routes have a `/*` in their
  53. * template
  54. *
  55. * @var string
  56. */
  57. protected $_greedy = false;
  58. /**
  59. * The compiled route regular expression
  60. *
  61. * @var string
  62. */
  63. protected $_compiledRoute = null;
  64. /**
  65. * HTTP header shortcut map. Used for evaluating header-based route expressions.
  66. *
  67. * @var array
  68. */
  69. protected $_headerMap = array(
  70. 'type' => 'content_type',
  71. 'method' => 'request_method',
  72. 'server' => 'server_name'
  73. );
  74. /**
  75. * Constructor for a Route
  76. *
  77. * @param string $template Template string with parameter placeholders
  78. * @param array $defaults Array of defaults for the route.
  79. * @param array $options Array of additional options for the Route
  80. */
  81. public function __construct($template, $defaults = array(), $options = array()) {
  82. $this->template = $template;
  83. $this->defaults = (array)$defaults;
  84. $this->options = (array)$options;
  85. }
  86. /**
  87. * Check if a Route has been compiled into a regular expression.
  88. *
  89. * @return boolean
  90. */
  91. public function compiled() {
  92. return !empty($this->_compiledRoute);
  93. }
  94. /**
  95. * Compiles the route's regular expression.
  96. *
  97. * Modifies defaults property so all necessary keys are set
  98. * and populates $this->names with the named routing elements.
  99. *
  100. * @return array Returns a string regular expression of the compiled route.
  101. */
  102. public function compile() {
  103. if ($this->compiled()) {
  104. return $this->_compiledRoute;
  105. }
  106. $this->_writeRoute();
  107. return $this->_compiledRoute;
  108. }
  109. /**
  110. * Builds a route regular expression.
  111. *
  112. * Uses the template, defaults and options properties to compile a
  113. * regular expression that can be used to parse request strings.
  114. *
  115. * @return void
  116. */
  117. protected function _writeRoute() {
  118. if (empty($this->template) || ($this->template === '/')) {
  119. $this->_compiledRoute = '#^/*$#';
  120. $this->keys = array();
  121. return;
  122. }
  123. $route = $this->template;
  124. $names = $routeParams = array();
  125. $parsed = preg_quote($this->template, '#');
  126. preg_match_all('#:([A-Za-z0-9_-]+[A-Z0-9a-z])#', $route, $namedElements);
  127. foreach ($namedElements[1] as $i => $name) {
  128. $search = '\\' . $namedElements[0][$i];
  129. if (isset($this->options[$name])) {
  130. $option = null;
  131. if ($name !== 'plugin' && array_key_exists($name, $this->defaults)) {
  132. $option = '?';
  133. }
  134. $slashParam = '/\\' . $namedElements[0][$i];
  135. if (strpos($parsed, $slashParam) !== false) {
  136. $routeParams[$slashParam] = '(?:/(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option;
  137. } else {
  138. $routeParams[$search] = '(?:(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option;
  139. }
  140. } else {
  141. $routeParams[$search] = '(?:(?P<' . $name . '>[^/]+))';
  142. }
  143. $names[] = $name;
  144. }
  145. if (preg_match('#\/\*\*$#', $route)) {
  146. $parsed = preg_replace('#/\\\\\*\\\\\*$#', '(?:/(?P<_trailing_>.*))?', $parsed);
  147. $this->_greedy = true;
  148. }
  149. if (preg_match('#\/\*$#', $route)) {
  150. $parsed = preg_replace('#/\\\\\*$#', '(?:/(?P<_args_>.*))?', $parsed);
  151. $this->_greedy = true;
  152. }
  153. krsort($routeParams);
  154. $parsed = str_replace(array_keys($routeParams), array_values($routeParams), $parsed);
  155. $this->_compiledRoute = '#^' . $parsed . '[/]*$#';
  156. $this->keys = $names;
  157. // Remove defaults that are also keys. They can cause match failures
  158. foreach ($this->keys as $key) {
  159. unset($this->defaults[$key]);
  160. }
  161. }
  162. /**
  163. * Checks to see if the given URL can be parsed by this route.
  164. *
  165. * If the route can be parsed an array of parameters will be returned; if not
  166. * false will be returned. String URLs are parsed if they match a routes regular expression.
  167. *
  168. * @param string $url The URL to attempt to parse.
  169. * @return mixed Boolean false on failure, otherwise an array or parameters
  170. */
  171. public function parse($url) {
  172. if (!$this->compiled()) {
  173. $this->compile();
  174. }
  175. if (!preg_match($this->_compiledRoute, urldecode($url), $route)) {
  176. return false;
  177. }
  178. foreach ($this->defaults as $key => $val) {
  179. $key = (string)$key;
  180. if ($key[0] === '[' && preg_match('/^\[(\w+)\]$/', $key, $header)) {
  181. if (isset($this->_headerMap[$header[1]])) {
  182. $header = $this->_headerMap[$header[1]];
  183. } else {
  184. $header = 'http_' . $header[1];
  185. }
  186. $header = strtoupper($header);
  187. $val = (array)$val;
  188. $h = false;
  189. foreach ($val as $v) {
  190. if (env($header) === $v) {
  191. $h = true;
  192. }
  193. }
  194. if (!$h) {
  195. return false;
  196. }
  197. }
  198. }
  199. array_shift($route);
  200. $count = count($this->keys);
  201. for ($i = 0; $i <= $count; $i++) {
  202. unset($route[$i]);
  203. }
  204. $route['pass'] = $route['named'] = array();
  205. // Assign defaults, set passed args to pass
  206. foreach ($this->defaults as $key => $value) {
  207. if (isset($route[$key])) {
  208. continue;
  209. }
  210. if (is_int($key)) {
  211. $route['pass'][] = $value;
  212. continue;
  213. }
  214. $route[$key] = $value;
  215. }
  216. foreach ($this->keys as $key) {
  217. if (isset($route[$key])) {
  218. $route[$key] = rawurldecode($route[$key]);
  219. }
  220. }
  221. if (isset($route['_args_'])) {
  222. list($pass, $named) = $this->_parseArgs($route['_args_'], $route);
  223. $route['pass'] = array_merge($route['pass'], $pass);
  224. $route['named'] = $named;
  225. unset($route['_args_']);
  226. }
  227. if (isset($route['_trailing_'])) {
  228. $route['pass'][] = rawurldecode($route['_trailing_']);
  229. unset($route['_trailing_']);
  230. }
  231. // restructure 'pass' key route params
  232. if (isset($this->options['pass'])) {
  233. $j = count($this->options['pass']);
  234. while ($j--) {
  235. if (isset($route[$this->options['pass'][$j]])) {
  236. array_unshift($route['pass'], $route[$this->options['pass'][$j]]);
  237. }
  238. }
  239. }
  240. return $route;
  241. }
  242. /**
  243. * Parse passed and Named parameters into a list of passed args, and a hash of named parameters.
  244. * The local and global configuration for named parameters will be used.
  245. *
  246. * @param string $args A string with the passed & named params. eg. /1/page:2
  247. * @param string $context The current route context, which should contain controller/action keys.
  248. * @return array Array of ($pass, $named)
  249. */
  250. protected function _parseArgs($args, $context) {
  251. $pass = $named = array();
  252. $args = explode('/', $args);
  253. $namedConfig = Router::namedConfig();
  254. $greedy = $namedConfig['greedyNamed'];
  255. $rules = $namedConfig['rules'];
  256. if (!empty($this->options['named'])) {
  257. $greedy = isset($this->options['greedyNamed']) && $this->options['greedyNamed'] === true;
  258. foreach ((array)$this->options['named'] as $key => $val) {
  259. if (is_numeric($key)) {
  260. $rules[$val] = true;
  261. continue;
  262. }
  263. $rules[$key] = $val;
  264. }
  265. }
  266. foreach ($args as $param) {
  267. if (empty($param) && $param !== '0' && $param !== 0) {
  268. continue;
  269. }
  270. $separatorIsPresent = strpos($param, $namedConfig['separator']) !== false;
  271. if ((!isset($this->options['named']) || !empty($this->options['named'])) && $separatorIsPresent) {
  272. list($key, $val) = explode($namedConfig['separator'], $param, 2);
  273. $key = rawurldecode($key);
  274. $val = rawurldecode($val);
  275. $hasRule = isset($rules[$key]);
  276. $passIt = (!$hasRule && !$greedy) || ($hasRule && !$this->_matchNamed($val, $rules[$key], $context));
  277. if ($passIt) {
  278. $pass[] = rawurldecode($param);
  279. } else {
  280. if (preg_match_all('/\[([A-Za-z0-9_-]+)?\]/', $key, $matches, PREG_SET_ORDER)) {
  281. $matches = array_reverse($matches);
  282. $parts = explode('[', $key);
  283. $key = array_shift($parts);
  284. $arr = $val;
  285. foreach ($matches as $match) {
  286. if (empty($match[1])) {
  287. $arr = array($arr);
  288. } else {
  289. $arr = array(
  290. $match[1] => $arr
  291. );
  292. }
  293. }
  294. $val = $arr;
  295. }
  296. $named = array_merge_recursive($named, array($key => $val));
  297. }
  298. } else {
  299. $pass[] = rawurldecode($param);
  300. }
  301. }
  302. return array($pass, $named);
  303. }
  304. /**
  305. * Check if a named parameter matches the current rules.
  306. *
  307. * Return true if a given named $param's $val matches a given $rule depending on $context.
  308. * Currently implemented rule types are controller, action and match that can be combined with each other.
  309. *
  310. * @param string $val The value of the named parameter
  311. * @param array $rule The rule(s) to apply, can also be a match string
  312. * @param string $context An array with additional context information (controller / action)
  313. * @return boolean
  314. */
  315. protected function _matchNamed($val, $rule, $context) {
  316. if ($rule === true || $rule === false) {
  317. return $rule;
  318. }
  319. if (is_string($rule)) {
  320. $rule = array('match' => $rule);
  321. }
  322. if (!is_array($rule)) {
  323. return false;
  324. }
  325. $controllerMatches = (
  326. !isset($rule['controller'], $context['controller']) ||
  327. in_array($context['controller'], (array)$rule['controller'])
  328. );
  329. if (!$controllerMatches) {
  330. return false;
  331. }
  332. $actionMatches = (
  333. !isset($rule['action'], $context['action']) ||
  334. in_array($context['action'], (array)$rule['action'])
  335. );
  336. if (!$actionMatches) {
  337. return false;
  338. }
  339. return (!isset($rule['match']) || preg_match('/' . $rule['match'] . '/', $val));
  340. }
  341. /**
  342. * Apply persistent parameters to an URL array. Persistent parameters are a special
  343. * key used during route creation to force route parameters to persist when omitted from
  344. * an URL array.
  345. *
  346. * @param array $url The array to apply persistent parameters to.
  347. * @param array $params An array of persistent values to replace persistent ones.
  348. * @return array An array with persistent parameters applied.
  349. */
  350. public function persistParams($url, $params) {
  351. foreach ($this->options['persist'] as $persistKey) {
  352. if (array_key_exists($persistKey, $params) && !isset($url[$persistKey])) {
  353. $url[$persistKey] = $params[$persistKey];
  354. }
  355. }
  356. return $url;
  357. }
  358. /**
  359. * Check if an URL array matches this route instance.
  360. *
  361. * If the URL matches the route parameters and settings, then
  362. * return a generated string URL. If the URL doesn't match the route parameters, false will be returned.
  363. * This method handles the reverse routing or conversion of URL arrays into string URLs.
  364. *
  365. * @param array $url An array of parameters to check matching with.
  366. * @return mixed Either a string URL for the parameters if they match or false.
  367. */
  368. public function match($url) {
  369. if (!$this->compiled()) {
  370. $this->compile();
  371. }
  372. $defaults = $this->defaults;
  373. if (isset($defaults['prefix'])) {
  374. $url['prefix'] = $defaults['prefix'];
  375. }
  376. //check that all the key names are in the url
  377. $keyNames = array_flip($this->keys);
  378. if (array_intersect_key($keyNames, $url) !== $keyNames) {
  379. return false;
  380. }
  381. // Missing defaults is a fail.
  382. if (array_diff_key($defaults, $url) !== array()) {
  383. return false;
  384. }
  385. $namedConfig = Router::namedConfig();
  386. $prefixes = Router::prefixes();
  387. $greedyNamed = $namedConfig['greedyNamed'];
  388. $allowedNamedParams = $namedConfig['rules'];
  389. $named = $pass = array();
  390. foreach ($url as $key => $value) {
  391. // keys that exist in the defaults and have different values is a match failure.
  392. $defaultExists = array_key_exists($key, $defaults);
  393. if ($defaultExists && $defaults[$key] != $value) {
  394. return false;
  395. } elseif ($defaultExists) {
  396. continue;
  397. }
  398. // If the key is a routed key, its not different yet.
  399. if (array_key_exists($key, $keyNames)) {
  400. continue;
  401. }
  402. // pull out passed args
  403. $numeric = is_numeric($key);
  404. if ($numeric && isset($defaults[$key]) && $defaults[$key] == $value) {
  405. continue;
  406. } elseif ($numeric) {
  407. $pass[] = $value;
  408. unset($url[$key]);
  409. continue;
  410. }
  411. // pull out named params if named params are greedy or a rule exists.
  412. if (
  413. ($greedyNamed || isset($allowedNamedParams[$key])) &&
  414. ($value !== false && $value !== null) &&
  415. (!in_array($key, $prefixes))
  416. ) {
  417. $named[$key] = $value;
  418. continue;
  419. }
  420. // keys that don't exist are different.
  421. if (!$defaultExists && !empty($value)) {
  422. return false;
  423. }
  424. }
  425. //if a not a greedy route, no extra params are allowed.
  426. if (!$this->_greedy && (!empty($pass) || !empty($named))) {
  427. return false;
  428. }
  429. //check patterns for routed params
  430. if (!empty($this->options)) {
  431. foreach ($this->options as $key => $pattern) {
  432. if (array_key_exists($key, $url) && !preg_match('#^' . $pattern . '$#', $url[$key])) {
  433. return false;
  434. }
  435. }
  436. }
  437. return $this->_writeUrl(array_merge($url, compact('pass', 'named')));
  438. }
  439. /**
  440. * Converts a matching route array into an URL string.
  441. *
  442. * Composes the string URL using the template
  443. * used to create the route.
  444. *
  445. * @param array $params The params to convert to a string URL.
  446. * @return string Composed route string.
  447. */
  448. protected function _writeUrl($params) {
  449. if (isset($params['prefix'])) {
  450. $prefixed = $params['prefix'] . '_';
  451. }
  452. if (isset($prefixed, $params['action']) && strpos($params['action'], $prefixed) === 0) {
  453. $params['action'] = substr($params['action'], strlen($prefixed) * -1);
  454. unset($params['prefix']);
  455. }
  456. if (is_array($params['pass'])) {
  457. $params['pass'] = implode('/', array_map('rawurlencode', $params['pass']));
  458. }
  459. $namedConfig = Router::namedConfig();
  460. $separator = $namedConfig['separator'];
  461. if (!empty($params['named']) && is_array($params['named'])) {
  462. $named = array();
  463. foreach ($params['named'] as $key => $value) {
  464. if (is_array($value)) {
  465. $flat = Hash::flatten($value, '%5D%5B');
  466. foreach ($flat as $namedKey => $namedValue) {
  467. $named[] = $key . "%5B{$namedKey}%5D" . $separator . rawurlencode($namedValue);
  468. }
  469. } else {
  470. $named[] = $key . $separator . rawurlencode($value);
  471. }
  472. }
  473. $params['pass'] = $params['pass'] . '/' . implode('/', $named);
  474. }
  475. $out = $this->template;
  476. $search = $replace = array();
  477. foreach ($this->keys as $key) {
  478. $string = null;
  479. if (isset($params[$key])) {
  480. $string = $params[$key];
  481. } elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
  482. $key .= '/';
  483. }
  484. $search[] = ':' . $key;
  485. $replace[] = $string;
  486. }
  487. $out = str_replace($search, $replace, $out);
  488. if (strpos($this->template, '*')) {
  489. $out = str_replace('*', $params['pass'], $out);
  490. }
  491. $out = str_replace('//', '/', $out);
  492. return $out;
  493. }
  494. }