123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774 |
- <?php
- /*
- * This file is part of the symfony package.
- * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
- *
- * For the full copyright and license information, please view the LICENSE
- * file that was distributed with this source code.
- */
- /**
- * sfRoute represents a route.
- *
- * @package symfony
- * @subpackage routing
- * @author Fabien Potencier <fabien.potencier@symfony-project.com>
- * @version SVN: $Id: sfRoute.class.php 13928 2008-12-10 21:54:55Z FabianLange $
- */
- class sfRoute implements Serializable
- {
- protected
- $isBound = false,
- $context = null,
- $parameters = null,
- $defaultParameters = array(),
- $defaultOptions = array(),
- $compiled = false,
- $options = array(),
- $pattern = null,
- $regex = null,
- $variables = array(),
- $defaults = array(),
- $requirements = array(),
- $tokens = array(),
- $customToken = false;
- /**
- * Constructor.
- *
- * Available options:
- *
- * * variable_prefixes: An array of characters that starts a variable name (: by default)
- * * segment_separators: An array of allowed characters for segment separators (/ and . by default)
- * * variable_regex: A regex that match a valid variable name ([\w\d_]+ by default)
- * * generate_shortest_url: Whether to generate the shortest URL possible (true by default)
- * * extra_parameters_as_query_string: Whether to generate extra parameters as a query string
- *
- * @param string $pattern The pattern to match
- * @param array $defaults An array of default parameter values
- * @param array $requirements An array of requirements for parameters (regexes)
- * @param array $options An array of options
- */
- public function __construct($pattern, array $defaults = array(), array $requirements = array(), array $options = array())
- {
- $this->pattern = trim($pattern);
- $this->defaults = $defaults;
- $this->requirements = $requirements;
- $this->options = $options;
- }
- /**
- * Binds the current route for a given context and parameters.
- *
- * @param array $context The context
- * @param array $parameters The parameters
- */
- public function bind($context, $parameters)
- {
- $this->isBound = true;
- $this->context = $context;
- $this->parameters = $parameters;
- }
- /**
- * Returns true if the form is bound to input values.
- *
- * @return Boolean true if the form is bound to input values, false otherwise
- */
- public function isBound()
- {
- return $this->isBound;
- }
- /**
- * Returns true if the URL matches this route, false otherwise.
- *
- * @param string $url The URL
- * @param array $context The context
- *
- * @return array An array of parameters
- */
- public function matchesUrl($url, $context = array())
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- if (!preg_match($this->regex, $url, $matches))
- {
- return false;
- }
- $defaults = array_merge($this->getDefaultParameters(), $this->defaults);
- $parameters = array();
- // *
- if (isset($matches['_star']))
- {
- $parameters = $this->parseStarParameter($matches['_star']);
- unset($matches['_star']);
- }
- // defaults
- $parameters = $this->mergeArrays($parameters, $defaults);
- // variables
- foreach ($matches as $key => $value)
- {
- if (!is_int($key))
- {
- $parameters[$key] = urldecode($value);
- }
- }
- return $parameters;
- }
- /**
- * Returns true if the parameters matches this route, false otherwise.
- *
- * @param mixed $params The parameters
- * @param array $context The context
- *
- * @return Boolean true if the parameters matches this route, false otherwise.
- */
- public function matchesParameters($params, $context = array())
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- if (!is_array($params))
- {
- return false;
- }
- $defaults = $this->mergeArrays($this->getDefaultParameters(), $this->defaults);
- $tparams = $this->mergeArrays($defaults, $params);
- // all $variables must be defined in the $tparams array
- if (array_diff_key($this->variables, $tparams))
- {
- return false;
- }
- // check requirements
- foreach (array_keys($this->variables) as $variable)
- {
- if (!$tparams[$variable])
- {
- continue;
- }
- if (!preg_match('#'.$this->requirements[$variable].'#', $tparams[$variable]))
- {
- return false;
- }
- }
- // all $params must be in $variables or $defaults if there is no * in route
- if (!$this->options['extra_parameters_as_query_string'])
- {
- if (false === strpos($this->regex, '<_star>') && array_diff_key($params, $this->variables, $defaults))
- {
- return false;
- }
- }
- // check that $params does not override a default value that is not a variable
- foreach ($defaults as $key => $value)
- {
- if (!isset($this->variables[$key]) && $tparams[$key] != $value)
- {
- return false;
- }
- }
- return true;
- }
- /**
- * Generates a URL from the given parameters.
- *
- * @param mixed $params The parameter values
- * @param array $context The context
- * @param Boolean $absolute Whether to generate an absolute URL
- *
- * @return string The generated URL
- */
- public function generate($params, $context = array(), $absolute = false)
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- $url = $this->pattern;
- $defaults = $this->mergeArrays($this->getDefaultParameters(), $this->defaults);
- $tparams = $this->mergeArrays($defaults, $params);
- // all params must be given
- if ($diff = array_diff_key($this->variables, $tparams))
- {
- throw new InvalidArgumentException(sprintf('The "%s" route has some missing mandatory parameters (%s).', $this->pattern, implode(', ', $diff)));
- }
- if ($this->options['generate_shortest_url'] || $this->customToken)
- {
- $url = $this->generateWithTokens($tparams);
- }
- else
- {
- // replace variables
- $variables = $this->variables;
- uasort($variables, create_function('$a, $b', 'return strlen($a) < strlen($b);'));
- foreach ($variables as $variable => $value)
- {
- $url = str_replace($value, urlencode($tparams[$variable]), $url);
- }
- }
- // replace extra parameters if the route contains *
- $url = $this->generateStarParameter($url, $defaults, $tparams);
- if ($this->options['extra_parameters_as_query_string'] && !$this->hasStarParameter())
- {
- // add a query string if needed
- if ($extra = array_diff_key($params, $this->variables, $defaults))
- {
- $url .= '?'.http_build_query($extra);
- }
- }
- return $url;
- }
- /**
- * Generates a URL for the given parameters by using the route tokens.
- *
- * @param array $parameters An array of parameters
- */
- protected function generateWithTokens($parameters)
- {
- $url = array();
- $optional = $this->options['generate_shortest_url'];
- $first = true;
- $tokens = array_reverse($this->tokens);
- foreach ($tokens as $token)
- {
- switch ($token[0])
- {
- case 'variable':
- if (!$optional || !isset($this->defaults[$token[3]]) || $parameters[$token[3]] != $this->defaults[$token[3]])
- {
- $url[] = urlencode($parameters[$token[3]]);
- $optional = false;
- }
- break;
- case 'text':
- $url[] = $token[2];
- $optional = false;
- break;
- case 'separator':
- if (false === $optional || $first)
- {
- $url[] = $token[2];
- }
- break;
- default:
- // handle custom tokens
- if ($segment = call_user_func_array(array($this, 'generateFor'.ucfirst(array_shift($token))), array_merge(array($optional, $parameters), $token)))
- {
- $url[] = $segment;
- $optional = false;
- }
- break;
- }
- $first = false;
- }
- $url = implode('', array_reverse($url));
- if (!$url)
- {
- $url = '/';
- }
- return $url;
- }
- /**
- * Returns the compiled pattern.
- *
- * @return string The compiled pattern
- */
- public function getPattern()
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- return $this->pattern;
- }
- /**
- * Returns the compiled regex.
- *
- * @return string The compiled regex
- */
- public function getRegex()
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- return $this->regex;
- }
- /**
- * Returns the compiled tokens.
- *
- * @return array The compiled tokens
- */
- public function getTokens()
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- return $this->tokens;
- }
- /**
- * Returns the compiled options.
- *
- * @return array The compiled options
- */
- public function getOptions()
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- return $this->options;
- }
- /**
- * Returns the compiled variables.
- *
- * @return array The compiled variables
- */
- public function getVariables()
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- return $this->variables;
- }
- /**
- * Returns the compiled defaults.
- *
- * @return array The compiled defaults
- */
- public function getDefaults()
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- return $this->defaults;
- }
- /**
- * Returns the compiled requirements.
- *
- * @return array The compiled requirements
- */
- public function getRequirements()
- {
- if (!$this->compiled)
- {
- $this->compile();
- }
- return $this->requirements;
- }
- /**
- * Compiles the current route instance.
- */
- protected function compile()
- {
- if ($this->compiled)
- {
- return;
- }
- $this->initializeOptions();
- $this->fixRequirements();
- $this->fixDefaults();
- $this->fixSuffix();
- $this->compiled = true;
- $this->firstOptional = 0;
- $this->segments = array();
- $this->preCompile();
- $this->tokenize();
- // parse
- foreach ($this->tokens as $token)
- {
- call_user_func_array(array($this, 'compileFor'.ucfirst(array_shift($token))), $token);
- }
- $this->postCompile();
- $separator = '';
- if (count($this->tokens))
- {
- $lastToken = $this->tokens[count($this->tokens) - 1];
- $separator = 'separator' == $lastToken[0] ? $lastToken[2] : '';
- }
- $this->regex = "#^\n".implode("\n", $this->segments)."\n".preg_quote($separator, '#')."$#x";
- }
- /**
- * Pre-compiles a route.
- */
- protected function preCompile()
- {
- // a route must start with a slash
- if (empty($this->pattern) || '/' != $this->pattern[0])
- {
- $this->pattern = '/'.$this->pattern;
- }
- }
- /**
- * Post-compiles a route.
- */
- protected function postCompile()
- {
- // all segments after the last static segment are optional
- // be careful, the n-1 is optional only if n is empty
- for ($i = $this->firstOptional, $max = count($this->segments); $i < $max; $i++)
- {
- $this->segments[$i] = (0 == $i ? '/?' : '').str_repeat(' ', $i - $this->firstOptional).'(?:'.$this->segments[$i];
- $this->segments[] = str_repeat(' ', $max - $i - 1).')?';
- }
- }
- /**
- * Tokenizes the route.
- */
- protected function tokenize()
- {
- $this->tokens = array();
- $buffer = $this->pattern;
- $afterASeparator = false;
- $currentSeparator = '';
- // a route is an array of (separator + variable) or (separator + text) segments
- while (strlen($buffer))
- {
- if (false !== $this->tokenizeBufferBefore($buffer, $tokens, $afterASeparator, $currentSeparator))
- {
- // a custom token
- $this->customToken = true;
- }
- else if ($afterASeparator && preg_match('#^'.$this->options['variable_prefix_regex'].'('.$this->options['variable_regex'].')#', $buffer, $match))
- {
- // a variable
- $this->tokens[] = array('variable', $currentSeparator, $match[0], $match[1]);
- $currentSeparator = '';
- $buffer = substr($buffer, strlen($match[0]));
- $afterASeparator = false;
- }
- else if ($afterASeparator && preg_match('#^('.$this->options['text_regex'].')(?:'.$this->options['segment_separators_regex'].'|$)#', $buffer, $match))
- {
- // a text
- $this->tokens[] = array('text', $currentSeparator, $match[1], null);
- $currentSeparator = '';
- $buffer = substr($buffer, strlen($match[1]));
- $afterASeparator = false;
- }
- else if (!$afterASeparator && preg_match('#^'.$this->options['segment_separators_regex'].'#', $buffer, $match))
- {
- // a separator
- $this->tokens[] = array('separator', $currentSeparator, $match[0], null);
- $currentSeparator = $match[0];
- $buffer = substr($buffer, strlen($match[0]));
- $afterASeparator = true;
- }
- else if (false !== $this->tokenizeBufferAfter($buffer, $tokens, $afterASeparator, $currentSeparator))
- {
- // a custom token
- $this->customToken = true;
- }
- else
- {
- // parsing problem
- throw new InvalidArgumentException(sprintf('Unable to parse "%s" route near "%s".', $this->pattern, $buffer));
- }
- }
- }
- /**
- * Tokenizes the buffer before default logic is applied.
- *
- * This method must return false if the buffer has not been parsed.
- *
- * @param string $buffer The current route buffer
- * @param array $tokens An array of current tokens
- * @param Boolean $afterASeparator Whether the buffer is just after a separator
- * @param string $currentSeparator The last matched separator
- *
- * @return Boolean true if a token has been generated, false otherwise
- */
- protected function tokenizeBufferBefore(&$buffer, &$tokens, &$afterASeparator, &$currentSeparator)
- {
- return false;
- }
- /**
- * Tokenizes the buffer after default logic is applied.
- *
- * This method must return false if the buffer has not been parsed.
- *
- * @param string $buffer The current route buffer
- * @param array $tokens An array of current tokens
- * @param Boolean $afterASeparator Whether the buffer is just after a separator
- * @param string $currentSeparator The last matched separator
- *
- * @return Boolean true if a token has been generated, false otherwise
- */
- protected function tokenizeBufferAfter(&$buffer, &$tokens, &$afterASeparator, &$currentSeparator)
- {
- return false;
- }
- protected function compileForText($separator, $text)
- {
- if ('*' == $text)
- {
- $this->segments[] = '(?:'.preg_quote($separator, '#').'(?P<_star>.*))?';
- }
- else
- {
- $this->firstOptional = count($this->segments) + 1;
- $this->segments[] = preg_quote($separator, '#').preg_quote($text, '#');
- }
- }
- protected function compileForVariable($separator, $name, $variable)
- {
- if (!isset($this->requirements[$variable]))
- {
- $this->requirements[$variable] = $this->options['variable_content_regex'];
- }
- $this->segments[] = preg_quote($separator, '#').'(?P<'.$variable.'>'.$this->requirements[$variable].')';
- $this->variables[$variable] = $name;
- if (!isset($this->defaults[$variable]))
- {
- $this->firstOptional = count($this->segments);
- }
- }
- protected function compileForSeparator($separator, $regexSeparator)
- {
- }
- public function getDefaultParameters()
- {
- return $this->defaultParameters;
- }
- public function setDefaultParameters($parameters)
- {
- $this->defaultParameters = $parameters;
- }
- public function getDefaultOptions()
- {
- return $this->defaultOptions;
- }
- public function setDefaultOptions($options)
- {
- $this->compiled = false;
- $this->defaultOptions = $options;
- }
- protected function initializeOptions()
- {
- $this->options = array_merge(array(
- 'suffix' => '',
- 'variable_prefixes' => array(':'),
- 'segment_separators' => array('/', '.'),
- 'variable_regex' => '[\w\d_]+',
- 'text_regex' => '.+?',
- 'generate_shortest_url' => true,
- 'extra_parameters_as_query_string' => true,
- ), $this->getDefaultOptions(), $this->options);
- // compute some regexes
- $this->options['variable_prefix_regex'] = '(?:'.implode('|', array_map(create_function('$a', 'return preg_quote($a, \'#\');'), $this->options['variable_prefixes'])).')';
- $this->options['segment_separators_regex'] = '(?:'.implode('|', array_map(create_function('$a', 'return preg_quote($a, \'#\');'), $this->options['segment_separators'])).')';
- $this->options['variable_content_regex'] = '[^'.implode('', array_map(create_function('$a', 'return str_replace(\'-\', \'\-\', preg_quote($a, \'#\'));'), $this->options['segment_separators'])).']+';
- }
- protected function parseStarParameter($star)
- {
- $parameters = array();
- $tmp = explode('/', $star);
- for ($i = 0, $max = count($tmp); $i < $max; $i += 2)
- {
- //dont allow a param name to be empty - #4173
- if (!empty($tmp[$i]))
- {
- $parameters[$tmp[$i]] = isset($tmp[$i + 1]) ? urldecode($tmp[$i + 1]) : true;
- }
- }
- return $parameters;
- }
- protected function hasStarParameter()
- {
- return false !== strpos($this->regex, '<_star>');
- }
- protected function generateStarParameter($url, $defaults, $parameters)
- {
- if (false === strpos($this->regex, '<_star>'))
- {
- return $url;
- }
- $tmp = array();
- foreach (array_diff_key($parameters, $this->variables, $defaults) as $key => $value)
- {
- if (is_array($value))
- {
- foreach ($value as $v)
- {
- $tmp[] = $key.'='.urlencode($v);
- }
- }
- else
- {
- $tmp[] = urlencode($key).'/'.urlencode($value);
- }
- }
- $tmp = implode('/', $tmp);
- if ($tmp)
- {
- $tmp = '/'.$tmp;
- }
- return preg_replace('#'.$this->options['segment_separators_regex'].'\*('.$this->options['segment_separators_regex'].'|$)#', "$tmp$1", $url);
- }
- protected function mergeArrays($arr1, $arr2)
- {
- foreach ($arr2 as $key => $value)
- {
- $arr1[$key] = $value;
- }
- return $arr1;
- }
- protected function fixDefaults()
- {
- foreach ($this->defaults as $key => $value)
- {
- if (ctype_digit($key))
- {
- $this->defaults[$value] = true;
- }
- else
- {
- $this->defaults[$key] = urldecode($value);
- }
- }
- }
- protected function fixRequirements()
- {
- foreach ($this->requirements as $key => $regex)
- {
- if (!is_string($regex))
- {
- continue;
- }
- if ('^' == $regex[0])
- {
- $regex = substr($regex, 1);
- }
- if ('$' == substr($regex, -1))
- {
- $regex = substr($regex, 0, -1);
- }
- $this->requirements[$key] = $regex;
- }
- }
- protected function fixSuffix()
- {
- if ('/' == $this->pattern[strlen($this->pattern) - 1])
- {
- // route ends by / (directory)
- }
- else if ('.' == $this->pattern[strlen($this->pattern) - 1])
- {
- // route ends by . (no suffix)
- $this->pattern = substr($this->pattern, 0, strlen($this->pattern) -1);
- }
- else if (preg_match('#\.(?:'.$this->options['variable_prefix_regex'].$this->options['variable_regex'].'|'.$this->options['variable_content_regex'].')$#i', $this->pattern))
- {
- // specific suffix for this route
- // a . with a variable after or some cars without any separators
- }
- else
- {
- $this->pattern .= $this->options['suffix'];
- }
- }
- public function serialize()
- {
- // always serialize compiled routes
- $this->compile();
- return serialize(array($this->tokens, $this->defaultParameters, $this->defaultOptions, $this->compiled, $this->options, $this->pattern, $this->regex, $this->variables, $this->defaults, $this->requirements));
- }
- public function unserialize($data)
- {
- list($this->tokens, $this->defaultParameters, $this->defaultOptions, $this->compiled, $this->options, $this->pattern, $this->regex, $this->variables, $this->defaults, $this->requirements) = unserialize($data);
- }
- }
|