Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12345 anikendra 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
 
16
App::uses('Hash', 'Utility');
17
 
18
/**
19
 * A single Route used by the Router to connect requests to
20
 * parameter maps.
21
 *
22
 * Not normally created as a standalone. Use Router::connect() to create
23
 * Routes for your application.
24
 *
25
 * @package Cake.Routing.Route
26
 */
27
class CakeRoute {
28
 
29
/**
30
 * An array of named segments in a Route.
31
 * `/:controller/:action/:id` has 3 key elements
32
 *
33
 * @var array
34
 */
35
	public $keys = array();
36
 
37
/**
38
 * An array of additional parameters for the Route.
39
 *
40
 * @var array
41
 */
42
	public $options = array();
43
 
44
/**
45
 * Default parameters for a Route
46
 *
47
 * @var array
48
 */
49
	public $defaults = array();
50
 
51
/**
52
 * The routes template string.
53
 *
54
 * @var string
55
 */
56
	public $template = null;
57
 
58
/**
59
 * Is this route a greedy route?  Greedy routes have a `/*` in their
60
 * template
61
 *
62
 * @var string
63
 */
64
	protected $_greedy = false;
65
 
66
/**
67
 * The compiled route regular expression
68
 *
69
 * @var string
70
 */
71
	protected $_compiledRoute = null;
72
 
73
/**
74
 * HTTP header shortcut map. Used for evaluating header-based route expressions.
75
 *
76
 * @var array
77
 */
78
	protected $_headerMap = array(
79
		'type' => 'content_type',
80
		'method' => 'request_method',
81
		'server' => 'server_name'
82
	);
83
 
84
/**
85
 * Constructor for a Route
86
 *
87
 * @param string $template Template string with parameter placeholders
88
 * @param array $defaults Array of defaults for the route.
89
 * @param array $options Array of additional options for the Route
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
 * Check if a Route has been compiled into a regular expression.
99
 *
100
 * @return bool
101
 */
102
	public function compiled() {
103
		return !empty($this->_compiledRoute);
104
	}
105
 
106
/**
107
 * Compiles the route's regular expression.
108
 *
109
 * Modifies defaults property so all necessary keys are set
110
 * and populates $this->names with the named routing elements.
111
 *
112
 * @return array Returns a string regular expression of the compiled route.
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
 * Builds a route regular expression.
124
 *
125
 * Uses the template, defaults and options properties to compile a
126
 * regular expression that can be used to parse request strings.
127
 *
128
 * @return void
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
		// Remove defaults that are also keys. They can cause match failures
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
 * Checks to see if the given URL can be parsed by this route.
184
 *
185
 * If the route can be parsed an array of parameters will be returned; if not
186
 * false will be returned. String URLs are parsed if they match a routes regular expression.
187
 *
188
 * @param string $url The URL to attempt to parse.
189
 * @return mixed Boolean false on failure, otherwise an array or parameters
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
		// Assign defaults, set passed args to pass
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
		// restructure 'pass' key route params
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
 * Parse passed and Named parameters into a list of passed args, and a hash of named parameters.
266
 * The local and global configuration for named parameters will be used.
267
 *
268
 * @param string $args A string with the passed & named params. eg. /1/page:2
269
 * @param string $context The current route context, which should contain controller/action keys.
270
 * @return array Array of ($pass, $named)
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
 * Check if a named parameter matches the current rules.
330
 *
331
 * Return true if a given named $param's $val matches a given $rule depending on $context.
332
 * Currently implemented rule types are controller, action and match that can be combined with each other.
333
 *
334
 * @param string $val The value of the named parameter
335
 * @param array $rule The rule(s) to apply, can also be a match string
336
 * @param string $context An array with additional context information (controller / action)
337
 * @return bool
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
 * Apply persistent parameters to a URL array. Persistent parameters are a special
369
 * key used during route creation to force route parameters to persist when omitted from
370
 * a URL array.
371
 *
372
 * @param array $url The array to apply persistent parameters to.
373
 * @param array $params An array of persistent values to replace persistent ones.
374
 * @return array An array with persistent parameters applied.
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
 * Check if a URL array matches this route instance.
390
 *
391
 * If the URL matches the route parameters and settings, then
392
 * return a generated string URL. If the URL doesn't match the route parameters, false will be returned.
393
 * This method handles the reverse routing or conversion of URL arrays into string URLs.
394
 *
395
 * @param array $url An array of parameters to check matching with.
396
 * @return mixed Either a string URL for the parameters if they match or false.
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
		//check that all the key names are in the url
409
		$keyNames = array_flip($this->keys);
410
		if (array_intersect_key($keyNames, $url) !== $keyNames) {
411
			return false;
412
		}
413
 
414
		// Missing defaults is a fail.
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
			// keys that exist in the defaults and have different values is a match failure.
428
			$defaultExists = array_key_exists($key, $defaults);
429
			if ($defaultExists && $defaults[$key] != $value) {
430
				return false;
431
			} elseif ($defaultExists) {
432
				continue;
433
			}
434
 
435
			// If the key is a routed key, its not different yet.
436
			if (array_key_exists($key, $keyNames)) {
437
				continue;
438
			}
439
 
440
			// pull out passed args
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
			// pull out named params if named params are greedy or a rule exists.
451
			if (
452
				($greedyNamed || isset($allowedNamedParams[$key])) &&
453
				($value !== false && $value !== null) &&
454
				(!in_array($key, $prefixes))
455
			) {
456
				$named[$key] = $value;
457
				continue;
458
			}
459
 
460
			// keys that don't exist are different.
461
			if (!$defaultExists && !empty($value)) {
462
				return false;
463
			}
464
		}
465
 
466
		//if a not a greedy route, no extra params are allowed.
467
		if (!$this->_greedy && (!empty($pass) || !empty($named))) {
468
			return false;
469
		}
470
 
471
		//check patterns for routed params
472
		if (!empty($this->options)) {
473
			foreach ($this->options as $key => $pattern) {
474
				if (array_key_exists($key, $url) && !preg_match('#^' . $pattern . '$#', $url[$key])) {
475
					return false;
476
				}
477
			}
478
		}
479
		return $this->_writeUrl(array_merge($url, compact('pass', 'named')));
480
	}
481
 
482
/**
483
 * Converts a matching route array into a URL string.
484
 *
485
 * Composes the string URL using the template
486
 * used to create the route.
487
 *
488
 * @param array $params The params to convert to a string URL.
489
 * @return string Composed route string.
490
 */
491
	protected function _writeUrl($params) {
492
		if (isset($params['prefix'])) {
493
			$prefixed = $params['prefix'] . '_';
494
		}
495
		if (isset($prefixed, $params['action']) && strpos($params['action'], $prefixed) === 0) {
496
			$params['action'] = substr($params['action'], strlen($prefixed));
497
			unset($params['prefix']);
498
		}
499
 
500
		if (is_array($params['pass'])) {
501
			$params['pass'] = implode('/', array_map('rawurlencode', $params['pass']));
502
		}
503
 
504
		$namedConfig = Router::namedConfig();
505
		$separator = $namedConfig['separator'];
506
 
507
		if (!empty($params['named']) && is_array($params['named'])) {
508
			$named = array();
509
			foreach ($params['named'] as $key => $value) {
510
				if (is_array($value)) {
511
					$flat = Hash::flatten($value, '%5D%5B');
512
					foreach ($flat as $namedKey => $namedValue) {
513
						$named[] = $key . "%5B{$namedKey}%5D" . $separator . rawurlencode($namedValue);
514
					}
515
				} else {
516
					$named[] = $key . $separator . rawurlencode($value);
517
				}
518
			}
519
			$params['pass'] = $params['pass'] . '/' . implode('/', $named);
520
		}
521
		$out = $this->template;
522
 
523
		if (!empty($this->keys)) {
524
			$search = $replace = array();
525
 
526
			foreach ($this->keys as $key) {
527
				$string = null;
528
				if (isset($params[$key])) {
529
					$string = $params[$key];
530
				} elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
531
					$key .= '/';
532
				}
533
				$search[] = ':' . $key;
534
				$replace[] = $string;
535
			}
536
			$out = str_replace($search, $replace, $out);
537
		}
538
 
539
		if (strpos($this->template, '**') !== false) {
540
			$out = str_replace('**', $params['pass'], $out);
541
			$out = str_replace('%2F', '/', $out);
542
		} elseif (strpos($this->template, '*') !== false) {
543
			$out = str_replace('*', $params['pass'], $out);
544
		}
545
		$out = str_replace('//', '/', $out);
546
		return $out;
547
	}
548
 
549
}