PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/manuperazafa/elsartenbackend
PHP | 549 lines | 343 code | 51 blank | 155 comment | 88 complexity | 8ed11cd1aa8ae33678ed84d7f2d7ae48 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 http://www.opensource.org/licenses/mit-license.php MIT License
  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 bool
  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. $keys = $this->keys;
  162. sort($keys);
  163. $this->keys = array_reverse($keys);
  164. }
  165. /**
  166. * Checks to see if the given URL can be parsed by this route.
  167. *
  168. * If the route can be parsed an array of parameters will be returned; if not
  169. * false will be returned. String URLs are parsed if they match a routes regular expression.
  170. *
  171. * @param string $url The URL to attempt to parse.
  172. * @return mixed Boolean false on failure, otherwise an array or parameters
  173. */
  174. public function parse($url) {
  175. if (!$this->compiled()) {
  176. $this->compile();
  177. }
  178. if (!preg_match($this->_compiledRoute, urldecode($url), $route)) {
  179. return false;
  180. }
  181. foreach ($this->defaults as $key => $val) {
  182. $key = (string)$key;
  183. if ($key[0] === '[' && preg_match('/^\[(\w+)\]$/', $key, $header)) {
  184. if (isset($this->_headerMap[$header[1]])) {
  185. $header = $this->_headerMap[$header[1]];
  186. } else {
  187. $header = 'http_' . $header[1];
  188. }
  189. $header = strtoupper($header);
  190. $val = (array)$val;
  191. $h = false;
  192. foreach ($val as $v) {
  193. if (env($header) === $v) {
  194. $h = true;
  195. }
  196. }
  197. if (!$h) {
  198. return false;
  199. }
  200. }
  201. }
  202. array_shift($route);
  203. $count = count($this->keys);
  204. for ($i = 0; $i <= $count; $i++) {
  205. unset($route[$i]);
  206. }
  207. $route['pass'] = $route['named'] = array();
  208. // Assign defaults, set passed args to pass
  209. foreach ($this->defaults as $key => $value) {
  210. if (isset($route[$key])) {
  211. continue;
  212. }
  213. if (is_int($key)) {
  214. $route['pass'][] = $value;
  215. continue;
  216. }
  217. $route[$key] = $value;
  218. }
  219. if (isset($route['_args_'])) {
  220. list($pass, $named) = $this->_parseArgs($route['_args_'], $route);
  221. $route['pass'] = array_merge($route['pass'], $pass);
  222. $route['named'] = $named;
  223. unset($route['_args_']);
  224. }
  225. if (isset($route['_trailing_'])) {
  226. $route['pass'][] = $route['_trailing_'];
  227. unset($route['_trailing_']);
  228. }
  229. // restructure 'pass' key route params
  230. if (isset($this->options['pass'])) {
  231. $j = count($this->options['pass']);
  232. while ($j--) {
  233. if (isset($route[$this->options['pass'][$j]])) {
  234. array_unshift($route['pass'], $route[$this->options['pass'][$j]]);
  235. }
  236. }
  237. }
  238. return $route;
  239. }
  240. /**
  241. * Parse passed and Named parameters into a list of passed args, and a hash of named parameters.
  242. * The local and global configuration for named parameters will be used.
  243. *
  244. * @param string $args A string with the passed & named params. eg. /1/page:2
  245. * @param string $context The current route context, which should contain controller/action keys.
  246. * @return array Array of ($pass, $named)
  247. */
  248. protected function _parseArgs($args, $context) {
  249. $pass = $named = array();
  250. $args = explode('/', $args);
  251. $namedConfig = Router::namedConfig();
  252. $greedy = $namedConfig['greedyNamed'];
  253. $rules = $namedConfig['rules'];
  254. if (!empty($this->options['named'])) {
  255. $greedy = isset($this->options['greedyNamed']) && $this->options['greedyNamed'] === true;
  256. foreach ((array)$this->options['named'] as $key => $val) {
  257. if (is_numeric($key)) {
  258. $rules[$val] = true;
  259. continue;
  260. }
  261. $rules[$key] = $val;
  262. }
  263. }
  264. foreach ($args as $param) {
  265. if (empty($param) && $param !== '0' && $param !== 0) {
  266. continue;
  267. }
  268. $separatorIsPresent = strpos($param, $namedConfig['separator']) !== false;
  269. if ((!isset($this->options['named']) || !empty($this->options['named'])) && $separatorIsPresent) {
  270. list($key, $val) = explode($namedConfig['separator'], $param, 2);
  271. $hasRule = isset($rules[$key]);
  272. $passIt = (!$hasRule && !$greedy) || ($hasRule && !$this->_matchNamed($val, $rules[$key], $context));
  273. if ($passIt) {
  274. $pass[] = $param;
  275. } else {
  276. if (preg_match_all('/\[([A-Za-z0-9_-]+)?\]/', $key, $matches, PREG_SET_ORDER)) {
  277. $matches = array_reverse($matches);
  278. $parts = explode('[', $key);
  279. $key = array_shift($parts);
  280. $arr = $val;
  281. foreach ($matches as $match) {
  282. if (empty($match[1])) {
  283. $arr = array($arr);
  284. } else {
  285. $arr = array(
  286. $match[1] => $arr
  287. );
  288. }
  289. }
  290. $val = $arr;
  291. }
  292. $named = array_merge_recursive($named, array($key => $val));
  293. }
  294. } else {
  295. $pass[] = $param;
  296. }
  297. }
  298. return array($pass, $named);
  299. }
  300. /**
  301. * Check if a named parameter matches the current rules.
  302. *
  303. * Return true if a given named $param's $val matches a given $rule depending on $context.
  304. * Currently implemented rule types are controller, action and match that can be combined with each other.
  305. *
  306. * @param string $val The value of the named parameter
  307. * @param array $rule The rule(s) to apply, can also be a match string
  308. * @param string $context An array with additional context information (controller / action)
  309. * @return bool
  310. */
  311. protected function _matchNamed($val, $rule, $context) {
  312. if ($rule === true || $rule === false) {
  313. return $rule;
  314. }
  315. if (is_string($rule)) {
  316. $rule = array('match' => $rule);
  317. }
  318. if (!is_array($rule)) {
  319. return false;
  320. }
  321. $controllerMatches = (
  322. !isset($rule['controller'], $context['controller']) ||
  323. in_array($context['controller'], (array)$rule['controller'])
  324. );
  325. if (!$controllerMatches) {
  326. return false;
  327. }
  328. $actionMatches = (
  329. !isset($rule['action'], $context['action']) ||
  330. in_array($context['action'], (array)$rule['action'])
  331. );
  332. if (!$actionMatches) {
  333. return false;
  334. }
  335. return (!isset($rule['match']) || preg_match('/' . $rule['match'] . '/', $val));
  336. }
  337. /**
  338. * Apply persistent parameters to a URL array. Persistent parameters are a special
  339. * key used during route creation to force route parameters to persist when omitted from
  340. * a URL array.
  341. *
  342. * @param array $url The array to apply persistent parameters to.
  343. * @param array $params An array of persistent values to replace persistent ones.
  344. * @return array An array with persistent parameters applied.
  345. */
  346. public function persistParams($url, $params) {
  347. if (empty($this->options['persist']) || !is_array($this->options['persist'])) {
  348. return $url;
  349. }
  350. foreach ($this->options['persist'] as $persistKey) {
  351. if (array_key_exists($persistKey, $params) && !isset($url[$persistKey])) {
  352. $url[$persistKey] = $params[$persistKey];
  353. }
  354. }
  355. return $url;
  356. }
  357. /**
  358. * Check if a URL array matches this route instance.
  359. *
  360. * If the URL matches the route parameters and settings, then
  361. * return a generated string URL. If the URL doesn't match the route parameters, false will be returned.
  362. * This method handles the reverse routing or conversion of URL arrays into string URLs.
  363. *
  364. * @param array $url An array of parameters to check matching with.
  365. * @return mixed Either a string URL for the parameters if they match or false.
  366. */
  367. public function match($url) {
  368. if (!$this->compiled()) {
  369. $this->compile();
  370. }
  371. $defaults = $this->defaults;
  372. if (isset($defaults['prefix'])) {
  373. $url['prefix'] = $defaults['prefix'];
  374. }
  375. //check that all the key names are in the url
  376. $keyNames = array_flip($this->keys);
  377. if (array_intersect_key($keyNames, $url) !== $keyNames) {
  378. return false;
  379. }
  380. // Missing defaults is a fail.
  381. if (array_diff_key($defaults, $url) !== array()) {
  382. return false;
  383. }
  384. $namedConfig = Router::namedConfig();
  385. $prefixes = Router::prefixes();
  386. $greedyNamed = $namedConfig['greedyNamed'];
  387. $allowedNamedParams = $namedConfig['rules'];
  388. $named = $pass = array();
  389. foreach ($url as $key => $value) {
  390. // keys that exist in the defaults and have different values is a match failure.
  391. $defaultExists = array_key_exists($key, $defaults);
  392. if ($defaultExists && $defaults[$key] != $value) {
  393. return false;
  394. } elseif ($defaultExists) {
  395. continue;
  396. }
  397. // If the key is a routed key, its not different yet.
  398. if (array_key_exists($key, $keyNames)) {
  399. continue;
  400. }
  401. // pull out passed args
  402. $numeric = is_numeric($key);
  403. if ($numeric && isset($defaults[$key]) && $defaults[$key] == $value) {
  404. continue;
  405. } elseif ($numeric) {
  406. $pass[] = $value;
  407. unset($url[$key]);
  408. continue;
  409. }
  410. // pull out named params if named params are greedy or a rule exists.
  411. if (
  412. ($greedyNamed || isset($allowedNamedParams[$key])) &&
  413. ($value !== false && $value !== null) &&
  414. (!in_array($key, $prefixes))
  415. ) {
  416. $named[$key] = $value;
  417. continue;
  418. }
  419. // keys that don't exist are different.
  420. if (!$defaultExists && !empty($value)) {
  421. return false;
  422. }
  423. }
  424. //if a not a greedy route, no extra params are allowed.
  425. if (!$this->_greedy && (!empty($pass) || !empty($named))) {
  426. return false;
  427. }
  428. //check patterns for routed params
  429. if (!empty($this->options)) {
  430. foreach ($this->options as $key => $pattern) {
  431. if (array_key_exists($key, $url) && !preg_match('#^' . $pattern . '$#', $url[$key])) {
  432. return false;
  433. }
  434. }
  435. }
  436. return $this->_writeUrl(array_merge($url, compact('pass', 'named')));
  437. }
  438. /**
  439. * Converts a matching route array into a URL string.
  440. *
  441. * Composes the string URL using the template
  442. * used to create the route.
  443. *
  444. * @param array $params The params to convert to a string URL.
  445. * @return string Composed route string.
  446. */
  447. protected function _writeUrl($params) {
  448. if (isset($params['prefix'])) {
  449. $prefixed = $params['prefix'] . '_';
  450. }
  451. if (isset($prefixed, $params['action']) && strpos($params['action'], $prefixed) === 0) {
  452. $params['action'] = substr($params['action'], strlen($prefixed));
  453. unset($params['prefix']);
  454. }
  455. if (is_array($params['pass'])) {
  456. $params['pass'] = implode('/', array_map('rawurlencode', $params['pass']));
  457. }
  458. $namedConfig = Router::namedConfig();
  459. $separator = $namedConfig['separator'];
  460. if (!empty($params['named']) && is_array($params['named'])) {
  461. $named = array();
  462. foreach ($params['named'] as $key => $value) {
  463. if (is_array($value)) {
  464. $flat = Hash::flatten($value, '%5D%5B');
  465. foreach ($flat as $namedKey => $namedValue) {
  466. $named[] = $key . "%5B{$namedKey}%5D" . $separator . rawurlencode($namedValue);
  467. }
  468. } else {
  469. $named[] = $key . $separator . rawurlencode($value);
  470. }
  471. }
  472. $params['pass'] = $params['pass'] . '/' . implode('/', $named);
  473. }
  474. $out = $this->template;
  475. if (!empty($this->keys)) {
  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. }
  489. if (strpos($this->template, '**') !== false) {
  490. $out = str_replace('**', $params['pass'], $out);
  491. $out = str_replace('%2F', '/', $out);
  492. } elseif (strpos($this->template, '*') !== false) {
  493. $out = str_replace('*', $params['pass'], $out);
  494. }
  495. $out = str_replace('//', '/', $out);
  496. return $out;
  497. }
  498. }