1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14:
15:
16: App::uses('Hash', 'Utility');
17:
18: 19: 20: 21: 22: 23: 24: 25: 26:
27: class CakeRoute {
28:
29: 30: 31: 32: 33: 34:
35: public $keys = array();
36:
37: 38: 39: 40: 41:
42: public $options = array();
43:
44: 45: 46: 47: 48:
49: public $defaults = array();
50:
51: 52: 53: 54: 55:
56: public $template = null;
57:
58: 59: 60: 61: 62: 63:
64: protected $_greedy = false;
65:
66: 67: 68: 69: 70:
71: protected $_compiledRoute = null;
72:
73: 74: 75: 76: 77:
78: protected $_headerMap = array(
79: 'type' => 'content_type',
80: 'method' => 'request_method',
81: 'server' => 'server_name'
82: );
83:
84: 85: 86: 87: 88: 89: 90:
91: public function __construct($template, $defaults = array(), $options = array()) {
92: $this->template = $template;
93: $this->defaults = (array)$defaults;
94: $this->options = (array)$options;
95: }
96:
97: 98: 99: 100: 101:
102: public function compiled() {
103: return !empty($this->_compiledRoute);
104: }
105:
106: 107: 108: 109: 110: 111: 112: 113:
114: public function compile() {
115: if ($this->compiled()) {
116: return $this->_compiledRoute;
117: }
118: $this->_writeRoute();
119: return $this->_compiledRoute;
120: }
121:
122: 123: 124: 125: 126: 127: 128: 129:
130: protected function _writeRoute() {
131: if (empty($this->template) || ($this->template === '/')) {
132: $this->_compiledRoute = '#^/*$#';
133: $this->keys = array();
134: return;
135: }
136: $route = $this->template;
137: $names = $routeParams = array();
138: $parsed = preg_quote($this->template, '#');
139:
140: preg_match_all('#:([A-Za-z0-9_-]+[A-Z0-9a-z])#', $route, $namedElements);
141: foreach ($namedElements[1] as $i => $name) {
142: $search = '\\' . $namedElements[0][$i];
143: if (isset($this->options[$name])) {
144: $option = null;
145: if ($name !== 'plugin' && array_key_exists($name, $this->defaults)) {
146: $option = '?';
147: }
148: $slashParam = '/\\' . $namedElements[0][$i];
149: if (strpos($parsed, $slashParam) !== false) {
150: $routeParams[$slashParam] = '(?:/(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option;
151: } else {
152: $routeParams[$search] = '(?:(?P<' . $name . '>' . $this->options[$name] . ')' . $option . ')' . $option;
153: }
154: } else {
155: $routeParams[$search] = '(?:(?P<' . $name . '>[^/]+))';
156: }
157: $names[] = $name;
158: }
159: if (preg_match('#\/\*\*$#', $route)) {
160: $parsed = preg_replace('#/\\\\\*\\\\\*$#', '(?:/(?P<_trailing_>.*))?', $parsed);
161: $this->_greedy = true;
162: }
163: if (preg_match('#\/\*$#', $route)) {
164: $parsed = preg_replace('#/\\\\\*$#', '(?:/(?P<_args_>.*))?', $parsed);
165: $this->_greedy = true;
166: }
167: krsort($routeParams);
168: $parsed = str_replace(array_keys($routeParams), array_values($routeParams), $parsed);
169: $this->_compiledRoute = '#^' . $parsed . '[/]*$#';
170: $this->keys = $names;
171:
172:
173: foreach ($this->keys as $key) {
174: unset($this->defaults[$key]);
175: }
176:
177: $keys = $this->keys;
178: sort($keys);
179: $this->keys = array_reverse($keys);
180: }
181:
182: 183: 184: 185: 186: 187: 188: 189: 190:
191: public function parse($url) {
192: if (!$this->compiled()) {
193: $this->compile();
194: }
195: if (!preg_match($this->_compiledRoute, urldecode($url), $route)) {
196: return false;
197: }
198: foreach ($this->defaults as $key => $val) {
199: $key = (string)$key;
200: if ($key[0] === '[' && preg_match('/^\[(\w+)\]$/', $key, $header)) {
201: if (isset($this->_headerMap[$header[1]])) {
202: $header = $this->_headerMap[$header[1]];
203: } else {
204: $header = 'http_' . $header[1];
205: }
206: $header = strtoupper($header);
207:
208: $val = (array)$val;
209: $h = false;
210:
211: foreach ($val as $v) {
212: if (env($header) === $v) {
213: $h = true;
214: }
215: }
216: if (!$h) {
217: return false;
218: }
219: }
220: }
221: array_shift($route);
222: $count = count($this->keys);
223: for ($i = 0; $i <= $count; $i++) {
224: unset($route[$i]);
225: }
226: $route['pass'] = $route['named'] = array();
227:
228:
229: foreach ($this->defaults as $key => $value) {
230: if (isset($route[$key])) {
231: continue;
232: }
233: if (is_int($key)) {
234: $route['pass'][] = $value;
235: continue;
236: }
237: $route[$key] = $value;
238: }
239:
240: if (isset($route['_args_'])) {
241: list($pass, $named) = $this->_parseArgs($route['_args_'], $route);
242: $route['pass'] = array_merge($route['pass'], $pass);
243: $route['named'] = $named;
244: unset($route['_args_']);
245: }
246:
247: if (isset($route['_trailing_'])) {
248: $route['pass'][] = $route['_trailing_'];
249: unset($route['_trailing_']);
250: }
251:
252:
253: if (isset($this->options['pass'])) {
254: $j = count($this->options['pass']);
255: while ($j--) {
256: if (isset($route[$this->options['pass'][$j]])) {
257: array_unshift($route['pass'], $route[$this->options['pass'][$j]]);
258: }
259: }
260: }
261: return $route;
262: }
263:
264: 265: 266: 267: 268: 269: 270: 271:
272: protected function _parseArgs($args, $context) {
273: $pass = $named = array();
274: $args = explode('/', $args);
275:
276: $namedConfig = Router::namedConfig();
277: $greedy = $namedConfig['greedyNamed'];
278: $rules = $namedConfig['rules'];
279: if (!empty($this->options['named'])) {
280: $greedy = isset($this->options['greedyNamed']) && $this->options['greedyNamed'] === true;
281: foreach ((array)$this->options['named'] as $key => $val) {
282: if (is_numeric($key)) {
283: $rules[$val] = true;
284: continue;
285: }
286: $rules[$key] = $val;
287: }
288: }
289:
290: foreach ($args as $param) {
291: if (empty($param) && $param !== '0' && $param !== 0) {
292: continue;
293: }
294:
295: $separatorIsPresent = strpos($param, $namedConfig['separator']) !== false;
296: if ((!isset($this->options['named']) || !empty($this->options['named'])) && $separatorIsPresent) {
297: list($key, $val) = explode($namedConfig['separator'], $param, 2);
298: $hasRule = isset($rules[$key]);
299: $passIt = (!$hasRule && !$greedy) || ($hasRule && !$this->_matchNamed($val, $rules[$key], $context));
300: if ($passIt) {
301: $pass[] = $param;
302: } else {
303: if (preg_match_all('/\[([A-Za-z0-9_-]+)?\]/', $key, $matches, PREG_SET_ORDER)) {
304: $matches = array_reverse($matches);
305: $parts = explode('[', $key);
306: $key = array_shift($parts);
307: $arr = $val;
308: foreach ($matches as $match) {
309: if (empty($match[1])) {
310: $arr = array($arr);
311: } else {
312: $arr = array(
313: $match[1] => $arr
314: );
315: }
316: }
317: $val = $arr;
318: }
319: $named = array_merge_recursive($named, array($key => $val));
320: }
321: } else {
322: $pass[] = $param;
323: }
324: }
325: return array($pass, $named);
326: }
327:
328: 329: 330: 331: 332: 333: 334: 335: 336: 337: 338:
339: protected function _matchNamed($val, $rule, $context) {
340: if ($rule === true || $rule === false) {
341: return $rule;
342: }
343: if (is_string($rule)) {
344: $rule = array('match' => $rule);
345: }
346: if (!is_array($rule)) {
347: return false;
348: }
349:
350: $controllerMatches = (
351: !isset($rule['controller'], $context['controller']) ||
352: in_array($context['controller'], (array)$rule['controller'])
353: );
354: if (!$controllerMatches) {
355: return false;
356: }
357: $actionMatches = (
358: !isset($rule['action'], $context['action']) ||
359: in_array($context['action'], (array)$rule['action'])
360: );
361: if (!$actionMatches) {
362: return false;
363: }
364: return (!isset($rule['match']) || preg_match('/' . $rule['match'] . '/', $val));
365: }
366:
367: 368: 369: 370: 371: 372: 373: 374: 375:
376: public function persistParams($url, $params) {
377: if (empty($this->options['persist']) || !is_array($this->options['persist'])) {
378: return $url;
379: }
380: foreach ($this->options['persist'] as $persistKey) {
381: if (array_key_exists($persistKey, $params) && !isset($url[$persistKey])) {
382: $url[$persistKey] = $params[$persistKey];
383: }
384: }
385: return $url;
386: }
387:
388: 389: 390: 391: 392: 393: 394: 395: 396: 397:
398: public function match($url) {
399: if (!$this->compiled()) {
400: $this->compile();
401: }
402: $defaults = $this->defaults;
403:
404: if (isset($defaults['prefix'])) {
405: $url['prefix'] = $defaults['prefix'];
406: }
407:
408:
409: $keyNames = array_flip($this->keys);
410: if (array_intersect_key($keyNames, $url) !== $keyNames) {
411: return false;
412: }
413:
414:
415: if (array_diff_key($defaults, $url) !== array()) {
416: return false;
417: }
418:
419: $namedConfig = Router::namedConfig();
420: $prefixes = Router::prefixes();
421: $greedyNamed = $namedConfig['greedyNamed'];
422: $allowedNamedParams = $namedConfig['rules'];
423:
424: $named = $pass = array();
425:
426: foreach ($url as $key => $value) {
427:
428: $defaultExists = array_key_exists($key, $defaults);
429: if ($defaultExists && $defaults[$key] != $value) {
430: return false;
431: } elseif ($defaultExists) {
432: continue;
433: }
434:
435:
436: if (array_key_exists($key, $keyNames)) {
437: continue;
438: }
439:
440:
441: $numeric = is_numeric($key);
442: if ($numeric && isset($defaults[$key]) && $defaults[$key] == $value) {
443: continue;
444: } elseif ($numeric) {
445: $pass[] = $value;
446: unset($url[$key]);
447: continue;
448: }
449:
450:
451: if (($greedyNamed || isset($allowedNamedParams[$key])) &&
452: ($value !== false && $value !== null) &&
453: (!in_array($key, $prefixes))
454: ) {
455: $named[$key] = $value;
456: continue;
457: }
458:
459:
460: if (!$defaultExists && !empty($value)) {
461: return false;
462: }
463: }
464:
465:
466: if (!$this->_greedy && (!empty($pass) || !empty($named))) {
467: return false;
468: }
469:
470:
471: if (!empty($this->options)) {
472: foreach ($this->options as $key => $pattern) {
473: if (array_key_exists($key, $url) && !preg_match('#^' . $pattern . '$#', $url[$key])) {
474: return false;
475: }
476: }
477: }
478: return $this->_writeUrl(array_merge($url, compact('pass', 'named')));
479: }
480:
481: 482: 483: 484: 485: 486: 487: 488: 489:
490: protected function _writeUrl($params) {
491: if (isset($params['prefix'])) {
492: $prefixed = $params['prefix'] . '_';
493: }
494: if (isset($prefixed, $params['action']) && strpos($params['action'], $prefixed) === 0) {
495: $params['action'] = substr($params['action'], strlen($prefixed));
496: unset($params['prefix']);
497: }
498:
499: if (is_array($params['pass'])) {
500: $params['pass'] = implode('/', array_map('rawurlencode', $params['pass']));
501: }
502:
503: $namedConfig = Router::namedConfig();
504: $separator = $namedConfig['separator'];
505:
506: if (!empty($params['named']) && is_array($params['named'])) {
507: $named = array();
508: foreach ($params['named'] as $key => $value) {
509: if (is_array($value)) {
510: $flat = Hash::flatten($value, '%5D%5B');
511: foreach ($flat as $namedKey => $namedValue) {
512: $named[] = $key . "%5B{$namedKey}%5D" . $separator . rawurlencode($namedValue);
513: }
514: } else {
515: $named[] = $key . $separator . rawurlencode($value);
516: }
517: }
518: $params['pass'] = $params['pass'] . '/' . implode('/', $named);
519: }
520: $out = $this->template;
521:
522: if (!empty($this->keys)) {
523: $search = $replace = array();
524:
525: foreach ($this->keys as $key) {
526: $string = null;
527: if (isset($params[$key])) {
528: $string = $params[$key];
529: } elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
530: $key .= '/';
531: }
532: $search[] = ':' . $key;
533: $replace[] = $string;
534: }
535: $out = str_replace($search, $replace, $out);
536: }
537:
538: if (strpos($this->template, '**') !== false) {
539: $out = str_replace('**', $params['pass'], $out);
540: $out = str_replace('%2F', '/', $out);
541: } elseif (strpos($this->template, '*') !== false) {
542: $out = str_replace('*', $params['pass'], $out);
543: }
544: $out = str_replace('//', '/', $out);
545: return $out;
546: }
547:
548: 549: 550: 551: 552: 553: 554: 555: 556:
557: public static function __set_state($fields) {
558: $class = function_exists('get_called_class') ? get_called_class() : __CLASS__;
559: $obj = new $class('');
560: foreach ($fields as $field => $value) {
561: $obj->$field = $value;
562: }
563: return $obj;
564: }
565:
566: }
567: