CakePHP
  • Documentation
    • Book
    • API
    • Videos
    • Reporting Security Issues
    • Privacy Policy
    • Logos & Trademarks
  • Business Solutions
  • Swag
  • Road Trip
  • Team
  • Community
    • Community
    • Get Involved
    • Issues (GitHub)
    • Bakery
    • Featured Resources
    • Training
    • Meetups
    • My CakePHP
    • CakeFest
    • Newsletter
    • Linkedin
    • YouTube
    • Facebook
    • Twitter
    • Mastodon
    • Help & Support
    • Forum
    • Stack Overflow
    • Slack
    • Paid Support
CakePHP

C CakePHP 2.0 API

  • Overview
  • Tree
  • Deprecated
  • Version:
    • 2.0
      • 4.2
      • 4.1
      • 4.0
      • 3.9
      • 3.8
      • 3.7
      • 3.6
      • 3.5
      • 3.4
      • 3.3
      • 3.2
      • 3.1
      • 3.0
      • 2.10
      • 2.9
      • 2.8
      • 2.7
      • 2.6
      • 2.5
      • 2.4
      • 2.3
      • 2.2
      • 2.1
      • 2.0
      • 1.3
      • 1.2

Packages

  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Auth
    • Core
    • Error
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
    • Network
      • Email
      • Http
    • Routing
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper

Classes

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

Generated using CakePHP API Docs