sfRoute.class.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  5. *
  6. * For the full copyright and license information, please view the LICENSE
  7. * file that was distributed with this source code.
  8. */
  9. /**
  10. * sfRoute represents a route.
  11. *
  12. * @package symfony
  13. * @subpackage routing
  14. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  15. * @version SVN: $Id: sfRoute.class.php 13928 2008-12-10 21:54:55Z FabianLange $
  16. */
  17. class sfRoute implements Serializable
  18. {
  19. protected
  20. $isBound = false,
  21. $context = null,
  22. $parameters = null,
  23. $defaultParameters = array(),
  24. $defaultOptions = array(),
  25. $compiled = false,
  26. $options = array(),
  27. $pattern = null,
  28. $regex = null,
  29. $variables = array(),
  30. $defaults = array(),
  31. $requirements = array(),
  32. $tokens = array(),
  33. $customToken = false;
  34. /**
  35. * Constructor.
  36. *
  37. * Available options:
  38. *
  39. * * variable_prefixes: An array of characters that starts a variable name (: by default)
  40. * * segment_separators: An array of allowed characters for segment separators (/ and . by default)
  41. * * variable_regex: A regex that match a valid variable name ([\w\d_]+ by default)
  42. * * generate_shortest_url: Whether to generate the shortest URL possible (true by default)
  43. * * extra_parameters_as_query_string: Whether to generate extra parameters as a query string
  44. *
  45. * @param string $pattern The pattern to match
  46. * @param array $defaults An array of default parameter values
  47. * @param array $requirements An array of requirements for parameters (regexes)
  48. * @param array $options An array of options
  49. */
  50. public function __construct($pattern, array $defaults = array(), array $requirements = array(), array $options = array())
  51. {
  52. $this->pattern = trim($pattern);
  53. $this->defaults = $defaults;
  54. $this->requirements = $requirements;
  55. $this->options = $options;
  56. }
  57. /**
  58. * Binds the current route for a given context and parameters.
  59. *
  60. * @param array $context The context
  61. * @param array $parameters The parameters
  62. */
  63. public function bind($context, $parameters)
  64. {
  65. $this->isBound = true;
  66. $this->context = $context;
  67. $this->parameters = $parameters;
  68. }
  69. /**
  70. * Returns true if the form is bound to input values.
  71. *
  72. * @return Boolean true if the form is bound to input values, false otherwise
  73. */
  74. public function isBound()
  75. {
  76. return $this->isBound;
  77. }
  78. /**
  79. * Returns true if the URL matches this route, false otherwise.
  80. *
  81. * @param string $url The URL
  82. * @param array $context The context
  83. *
  84. * @return array An array of parameters
  85. */
  86. public function matchesUrl($url, $context = array())
  87. {
  88. if (!$this->compiled)
  89. {
  90. $this->compile();
  91. }
  92. if (!preg_match($this->regex, $url, $matches))
  93. {
  94. return false;
  95. }
  96. $defaults = array_merge($this->getDefaultParameters(), $this->defaults);
  97. $parameters = array();
  98. // *
  99. if (isset($matches['_star']))
  100. {
  101. $parameters = $this->parseStarParameter($matches['_star']);
  102. unset($matches['_star']);
  103. }
  104. // defaults
  105. $parameters = $this->mergeArrays($parameters, $defaults);
  106. // variables
  107. foreach ($matches as $key => $value)
  108. {
  109. if (!is_int($key))
  110. {
  111. $parameters[$key] = urldecode($value);
  112. }
  113. }
  114. return $parameters;
  115. }
  116. /**
  117. * Returns true if the parameters matches this route, false otherwise.
  118. *
  119. * @param mixed $params The parameters
  120. * @param array $context The context
  121. *
  122. * @return Boolean true if the parameters matches this route, false otherwise.
  123. */
  124. public function matchesParameters($params, $context = array())
  125. {
  126. if (!$this->compiled)
  127. {
  128. $this->compile();
  129. }
  130. if (!is_array($params))
  131. {
  132. return false;
  133. }
  134. $defaults = $this->mergeArrays($this->getDefaultParameters(), $this->defaults);
  135. $tparams = $this->mergeArrays($defaults, $params);
  136. // all $variables must be defined in the $tparams array
  137. if (array_diff_key($this->variables, $tparams))
  138. {
  139. return false;
  140. }
  141. // check requirements
  142. foreach (array_keys($this->variables) as $variable)
  143. {
  144. if (!$tparams[$variable])
  145. {
  146. continue;
  147. }
  148. if (!preg_match('#'.$this->requirements[$variable].'#', $tparams[$variable]))
  149. {
  150. return false;
  151. }
  152. }
  153. // all $params must be in $variables or $defaults if there is no * in route
  154. if (!$this->options['extra_parameters_as_query_string'])
  155. {
  156. if (false === strpos($this->regex, '<_star>') && array_diff_key($params, $this->variables, $defaults))
  157. {
  158. return false;
  159. }
  160. }
  161. // check that $params does not override a default value that is not a variable
  162. foreach ($defaults as $key => $value)
  163. {
  164. if (!isset($this->variables[$key]) && $tparams[$key] != $value)
  165. {
  166. return false;
  167. }
  168. }
  169. return true;
  170. }
  171. /**
  172. * Generates a URL from the given parameters.
  173. *
  174. * @param mixed $params The parameter values
  175. * @param array $context The context
  176. * @param Boolean $absolute Whether to generate an absolute URL
  177. *
  178. * @return string The generated URL
  179. */
  180. public function generate($params, $context = array(), $absolute = false)
  181. {
  182. if (!$this->compiled)
  183. {
  184. $this->compile();
  185. }
  186. $url = $this->pattern;
  187. $defaults = $this->mergeArrays($this->getDefaultParameters(), $this->defaults);
  188. $tparams = $this->mergeArrays($defaults, $params);
  189. // all params must be given
  190. if ($diff = array_diff_key($this->variables, $tparams))
  191. {
  192. throw new InvalidArgumentException(sprintf('The "%s" route has some missing mandatory parameters (%s).', $this->pattern, implode(', ', $diff)));
  193. }
  194. if ($this->options['generate_shortest_url'] || $this->customToken)
  195. {
  196. $url = $this->generateWithTokens($tparams);
  197. }
  198. else
  199. {
  200. // replace variables
  201. $variables = $this->variables;
  202. uasort($variables, create_function('$a, $b', 'return strlen($a) < strlen($b);'));
  203. foreach ($variables as $variable => $value)
  204. {
  205. $url = str_replace($value, urlencode($tparams[$variable]), $url);
  206. }
  207. }
  208. // replace extra parameters if the route contains *
  209. $url = $this->generateStarParameter($url, $defaults, $tparams);
  210. if ($this->options['extra_parameters_as_query_string'] && !$this->hasStarParameter())
  211. {
  212. // add a query string if needed
  213. if ($extra = array_diff_key($params, $this->variables, $defaults))
  214. {
  215. $url .= '?'.http_build_query($extra);
  216. }
  217. }
  218. return $url;
  219. }
  220. /**
  221. * Generates a URL for the given parameters by using the route tokens.
  222. *
  223. * @param array $parameters An array of parameters
  224. */
  225. protected function generateWithTokens($parameters)
  226. {
  227. $url = array();
  228. $optional = $this->options['generate_shortest_url'];
  229. $first = true;
  230. $tokens = array_reverse($this->tokens);
  231. foreach ($tokens as $token)
  232. {
  233. switch ($token[0])
  234. {
  235. case 'variable':
  236. if (!$optional || !isset($this->defaults[$token[3]]) || $parameters[$token[3]] != $this->defaults[$token[3]])
  237. {
  238. $url[] = urlencode($parameters[$token[3]]);
  239. $optional = false;
  240. }
  241. break;
  242. case 'text':
  243. $url[] = $token[2];
  244. $optional = false;
  245. break;
  246. case 'separator':
  247. if (false === $optional || $first)
  248. {
  249. $url[] = $token[2];
  250. }
  251. break;
  252. default:
  253. // handle custom tokens
  254. if ($segment = call_user_func_array(array($this, 'generateFor'.ucfirst(array_shift($token))), array_merge(array($optional, $parameters), $token)))
  255. {
  256. $url[] = $segment;
  257. $optional = false;
  258. }
  259. break;
  260. }
  261. $first = false;
  262. }
  263. $url = implode('', array_reverse($url));
  264. if (!$url)
  265. {
  266. $url = '/';
  267. }
  268. return $url;
  269. }
  270. /**
  271. * Returns the compiled pattern.
  272. *
  273. * @return string The compiled pattern
  274. */
  275. public function getPattern()
  276. {
  277. if (!$this->compiled)
  278. {
  279. $this->compile();
  280. }
  281. return $this->pattern;
  282. }
  283. /**
  284. * Returns the compiled regex.
  285. *
  286. * @return string The compiled regex
  287. */
  288. public function getRegex()
  289. {
  290. if (!$this->compiled)
  291. {
  292. $this->compile();
  293. }
  294. return $this->regex;
  295. }
  296. /**
  297. * Returns the compiled tokens.
  298. *
  299. * @return array The compiled tokens
  300. */
  301. public function getTokens()
  302. {
  303. if (!$this->compiled)
  304. {
  305. $this->compile();
  306. }
  307. return $this->tokens;
  308. }
  309. /**
  310. * Returns the compiled options.
  311. *
  312. * @return array The compiled options
  313. */
  314. public function getOptions()
  315. {
  316. if (!$this->compiled)
  317. {
  318. $this->compile();
  319. }
  320. return $this->options;
  321. }
  322. /**
  323. * Returns the compiled variables.
  324. *
  325. * @return array The compiled variables
  326. */
  327. public function getVariables()
  328. {
  329. if (!$this->compiled)
  330. {
  331. $this->compile();
  332. }
  333. return $this->variables;
  334. }
  335. /**
  336. * Returns the compiled defaults.
  337. *
  338. * @return array The compiled defaults
  339. */
  340. public function getDefaults()
  341. {
  342. if (!$this->compiled)
  343. {
  344. $this->compile();
  345. }
  346. return $this->defaults;
  347. }
  348. /**
  349. * Returns the compiled requirements.
  350. *
  351. * @return array The compiled requirements
  352. */
  353. public function getRequirements()
  354. {
  355. if (!$this->compiled)
  356. {
  357. $this->compile();
  358. }
  359. return $this->requirements;
  360. }
  361. /**
  362. * Compiles the current route instance.
  363. */
  364. protected function compile()
  365. {
  366. if ($this->compiled)
  367. {
  368. return;
  369. }
  370. $this->initializeOptions();
  371. $this->fixRequirements();
  372. $this->fixDefaults();
  373. $this->fixSuffix();
  374. $this->compiled = true;
  375. $this->firstOptional = 0;
  376. $this->segments = array();
  377. $this->preCompile();
  378. $this->tokenize();
  379. // parse
  380. foreach ($this->tokens as $token)
  381. {
  382. call_user_func_array(array($this, 'compileFor'.ucfirst(array_shift($token))), $token);
  383. }
  384. $this->postCompile();
  385. $separator = '';
  386. if (count($this->tokens))
  387. {
  388. $lastToken = $this->tokens[count($this->tokens) - 1];
  389. $separator = 'separator' == $lastToken[0] ? $lastToken[2] : '';
  390. }
  391. $this->regex = "#^\n".implode("\n", $this->segments)."\n".preg_quote($separator, '#')."$#x";
  392. }
  393. /**
  394. * Pre-compiles a route.
  395. */
  396. protected function preCompile()
  397. {
  398. // a route must start with a slash
  399. if (empty($this->pattern) || '/' != $this->pattern[0])
  400. {
  401. $this->pattern = '/'.$this->pattern;
  402. }
  403. }
  404. /**
  405. * Post-compiles a route.
  406. */
  407. protected function postCompile()
  408. {
  409. // all segments after the last static segment are optional
  410. // be careful, the n-1 is optional only if n is empty
  411. for ($i = $this->firstOptional, $max = count($this->segments); $i < $max; $i++)
  412. {
  413. $this->segments[$i] = (0 == $i ? '/?' : '').str_repeat(' ', $i - $this->firstOptional).'(?:'.$this->segments[$i];
  414. $this->segments[] = str_repeat(' ', $max - $i - 1).')?';
  415. }
  416. }
  417. /**
  418. * Tokenizes the route.
  419. */
  420. protected function tokenize()
  421. {
  422. $this->tokens = array();
  423. $buffer = $this->pattern;
  424. $afterASeparator = false;
  425. $currentSeparator = '';
  426. // a route is an array of (separator + variable) or (separator + text) segments
  427. while (strlen($buffer))
  428. {
  429. if (false !== $this->tokenizeBufferBefore($buffer, $tokens, $afterASeparator, $currentSeparator))
  430. {
  431. // a custom token
  432. $this->customToken = true;
  433. }
  434. else if ($afterASeparator && preg_match('#^'.$this->options['variable_prefix_regex'].'('.$this->options['variable_regex'].')#', $buffer, $match))
  435. {
  436. // a variable
  437. $this->tokens[] = array('variable', $currentSeparator, $match[0], $match[1]);
  438. $currentSeparator = '';
  439. $buffer = substr($buffer, strlen($match[0]));
  440. $afterASeparator = false;
  441. }
  442. else if ($afterASeparator && preg_match('#^('.$this->options['text_regex'].')(?:'.$this->options['segment_separators_regex'].'|$)#', $buffer, $match))
  443. {
  444. // a text
  445. $this->tokens[] = array('text', $currentSeparator, $match[1], null);
  446. $currentSeparator = '';
  447. $buffer = substr($buffer, strlen($match[1]));
  448. $afterASeparator = false;
  449. }
  450. else if (!$afterASeparator && preg_match('#^'.$this->options['segment_separators_regex'].'#', $buffer, $match))
  451. {
  452. // a separator
  453. $this->tokens[] = array('separator', $currentSeparator, $match[0], null);
  454. $currentSeparator = $match[0];
  455. $buffer = substr($buffer, strlen($match[0]));
  456. $afterASeparator = true;
  457. }
  458. else if (false !== $this->tokenizeBufferAfter($buffer, $tokens, $afterASeparator, $currentSeparator))
  459. {
  460. // a custom token
  461. $this->customToken = true;
  462. }
  463. else
  464. {
  465. // parsing problem
  466. throw new InvalidArgumentException(sprintf('Unable to parse "%s" route near "%s".', $this->pattern, $buffer));
  467. }
  468. }
  469. }
  470. /**
  471. * Tokenizes the buffer before default logic is applied.
  472. *
  473. * This method must return false if the buffer has not been parsed.
  474. *
  475. * @param string $buffer The current route buffer
  476. * @param array $tokens An array of current tokens
  477. * @param Boolean $afterASeparator Whether the buffer is just after a separator
  478. * @param string $currentSeparator The last matched separator
  479. *
  480. * @return Boolean true if a token has been generated, false otherwise
  481. */
  482. protected function tokenizeBufferBefore(&$buffer, &$tokens, &$afterASeparator, &$currentSeparator)
  483. {
  484. return false;
  485. }
  486. /**
  487. * Tokenizes the buffer after default logic is applied.
  488. *
  489. * This method must return false if the buffer has not been parsed.
  490. *
  491. * @param string $buffer The current route buffer
  492. * @param array $tokens An array of current tokens
  493. * @param Boolean $afterASeparator Whether the buffer is just after a separator
  494. * @param string $currentSeparator The last matched separator
  495. *
  496. * @return Boolean true if a token has been generated, false otherwise
  497. */
  498. protected function tokenizeBufferAfter(&$buffer, &$tokens, &$afterASeparator, &$currentSeparator)
  499. {
  500. return false;
  501. }
  502. protected function compileForText($separator, $text)
  503. {
  504. if ('*' == $text)
  505. {
  506. $this->segments[] = '(?:'.preg_quote($separator, '#').'(?P<_star>.*))?';
  507. }
  508. else
  509. {
  510. $this->firstOptional = count($this->segments) + 1;
  511. $this->segments[] = preg_quote($separator, '#').preg_quote($text, '#');
  512. }
  513. }
  514. protected function compileForVariable($separator, $name, $variable)
  515. {
  516. if (!isset($this->requirements[$variable]))
  517. {
  518. $this->requirements[$variable] = $this->options['variable_content_regex'];
  519. }
  520. $this->segments[] = preg_quote($separator, '#').'(?P<'.$variable.'>'.$this->requirements[$variable].')';
  521. $this->variables[$variable] = $name;
  522. if (!isset($this->defaults[$variable]))
  523. {
  524. $this->firstOptional = count($this->segments);
  525. }
  526. }
  527. protected function compileForSeparator($separator, $regexSeparator)
  528. {
  529. }
  530. public function getDefaultParameters()
  531. {
  532. return $this->defaultParameters;
  533. }
  534. public function setDefaultParameters($parameters)
  535. {
  536. $this->defaultParameters = $parameters;
  537. }
  538. public function getDefaultOptions()
  539. {
  540. return $this->defaultOptions;
  541. }
  542. public function setDefaultOptions($options)
  543. {
  544. $this->compiled = false;
  545. $this->defaultOptions = $options;
  546. }
  547. protected function initializeOptions()
  548. {
  549. $this->options = array_merge(array(
  550. 'suffix' => '',
  551. 'variable_prefixes' => array(':'),
  552. 'segment_separators' => array('/', '.'),
  553. 'variable_regex' => '[\w\d_]+',
  554. 'text_regex' => '.+?',
  555. 'generate_shortest_url' => true,
  556. 'extra_parameters_as_query_string' => true,
  557. ), $this->getDefaultOptions(), $this->options);
  558. // compute some regexes
  559. $this->options['variable_prefix_regex'] = '(?:'.implode('|', array_map(create_function('$a', 'return preg_quote($a, \'#\');'), $this->options['variable_prefixes'])).')';
  560. $this->options['segment_separators_regex'] = '(?:'.implode('|', array_map(create_function('$a', 'return preg_quote($a, \'#\');'), $this->options['segment_separators'])).')';
  561. $this->options['variable_content_regex'] = '[^'.implode('', array_map(create_function('$a', 'return str_replace(\'-\', \'\-\', preg_quote($a, \'#\'));'), $this->options['segment_separators'])).']+';
  562. }
  563. protected function parseStarParameter($star)
  564. {
  565. $parameters = array();
  566. $tmp = explode('/', $star);
  567. for ($i = 0, $max = count($tmp); $i < $max; $i += 2)
  568. {
  569. //dont allow a param name to be empty - #4173
  570. if (!empty($tmp[$i]))
  571. {
  572. $parameters[$tmp[$i]] = isset($tmp[$i + 1]) ? urldecode($tmp[$i + 1]) : true;
  573. }
  574. }
  575. return $parameters;
  576. }
  577. protected function hasStarParameter()
  578. {
  579. return false !== strpos($this->regex, '<_star>');
  580. }
  581. protected function generateStarParameter($url, $defaults, $parameters)
  582. {
  583. if (false === strpos($this->regex, '<_star>'))
  584. {
  585. return $url;
  586. }
  587. $tmp = array();
  588. foreach (array_diff_key($parameters, $this->variables, $defaults) as $key => $value)
  589. {
  590. if (is_array($value))
  591. {
  592. foreach ($value as $v)
  593. {
  594. $tmp[] = $key.'='.urlencode($v);
  595. }
  596. }
  597. else
  598. {
  599. $tmp[] = urlencode($key).'/'.urlencode($value);
  600. }
  601. }
  602. $tmp = implode('/', $tmp);
  603. if ($tmp)
  604. {
  605. $tmp = '/'.$tmp;
  606. }
  607. return preg_replace('#'.$this->options['segment_separators_regex'].'\*('.$this->options['segment_separators_regex'].'|$)#', "$tmp$1", $url);
  608. }
  609. protected function mergeArrays($arr1, $arr2)
  610. {
  611. foreach ($arr2 as $key => $value)
  612. {
  613. $arr1[$key] = $value;
  614. }
  615. return $arr1;
  616. }
  617. protected function fixDefaults()
  618. {
  619. foreach ($this->defaults as $key => $value)
  620. {
  621. if (ctype_digit($key))
  622. {
  623. $this->defaults[$value] = true;
  624. }
  625. else
  626. {
  627. $this->defaults[$key] = urldecode($value);
  628. }
  629. }
  630. }
  631. protected function fixRequirements()
  632. {
  633. foreach ($this->requirements as $key => $regex)
  634. {
  635. if (!is_string($regex))
  636. {
  637. continue;
  638. }
  639. if ('^' == $regex[0])
  640. {
  641. $regex = substr($regex, 1);
  642. }
  643. if ('$' == substr($regex, -1))
  644. {
  645. $regex = substr($regex, 0, -1);
  646. }
  647. $this->requirements[$key] = $regex;
  648. }
  649. }
  650. protected function fixSuffix()
  651. {
  652. if ('/' == $this->pattern[strlen($this->pattern) - 1])
  653. {
  654. // route ends by / (directory)
  655. }
  656. else if ('.' == $this->pattern[strlen($this->pattern) - 1])
  657. {
  658. // route ends by . (no suffix)
  659. $this->pattern = substr($this->pattern, 0, strlen($this->pattern) -1);
  660. }
  661. else if (preg_match('#\.(?:'.$this->options['variable_prefix_regex'].$this->options['variable_regex'].'|'.$this->options['variable_content_regex'].')$#i', $this->pattern))
  662. {
  663. // specific suffix for this route
  664. // a . with a variable after or some cars without any separators
  665. }
  666. else
  667. {
  668. $this->pattern .= $this->options['suffix'];
  669. }
  670. }
  671. public function serialize()
  672. {
  673. // always serialize compiled routes
  674. $this->compile();
  675. return serialize(array($this->tokens, $this->defaultParameters, $this->defaultOptions, $this->compiled, $this->options, $this->pattern, $this->regex, $this->variables, $this->defaults, $this->requirements));
  676. }
  677. public function unserialize($data)
  678. {
  679. list($this->tokens, $this->defaultParameters, $this->defaultOptions, $this->compiled, $this->options, $this->pattern, $this->regex, $this->variables, $this->defaults, $this->requirements) = unserialize($data);
  680. }
  681. }