UrlGenerator.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Routing\Generator;
  11. use Symfony\Component\Routing\Route;
  12. use Symfony\Component\Routing\RouteCollection;
  13. use Symfony\Component\Routing\RequestContext;
  14. use Symfony\Component\Routing\Exception\InvalidParameterException;
  15. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  16. use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
  17. /**
  18. * UrlGenerator generates URL based on a set of routes.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class UrlGenerator implements UrlGeneratorInterface
  23. {
  24. protected $context;
  25. private $routes;
  26. private $cache;
  27. /**
  28. * Constructor.
  29. *
  30. * @param RouteCollection $routes A RouteCollection instance
  31. * @param RequestContext $context The context
  32. */
  33. public function __construct(RouteCollection $routes, RequestContext $context)
  34. {
  35. $this->routes = $routes;
  36. $this->context = $context;
  37. $this->cache = array();
  38. }
  39. /**
  40. * Sets the request context.
  41. *
  42. * @param RequestContext $context The context
  43. */
  44. public function setContext(RequestContext $context)
  45. {
  46. $this->context = $context;
  47. }
  48. /**
  49. * Gets the request context.
  50. *
  51. * @return RequestContext The context
  52. */
  53. public function getContext()
  54. {
  55. return $this->context;
  56. }
  57. /**
  58. * Generates a URL from the given parameters.
  59. *
  60. * @param string $name The name of the route
  61. * @param array $parameters An array of parameters
  62. * @param Boolean $absolute Whether to generate an absolute URL
  63. *
  64. * @return string The generated URL
  65. *
  66. * @throws Symfony\Component\Routing\Exception\RouteNotFoundException When route doesn't exist
  67. */
  68. public function generate($name, array $parameters = array(), $absolute = false)
  69. {
  70. if (null === $route = $this->routes->get($name)) {
  71. throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
  72. }
  73. if (!isset($this->cache[$name])) {
  74. $this->cache[$name] = $route->compile();
  75. }
  76. return $this->doGenerate($this->cache[$name]->getVariables(), $route->getDefaults(), $route->getRequirements(), $this->cache[$name]->getTokens(), $parameters, $name, $absolute);
  77. }
  78. /**
  79. * @throws Symfony\Component\Routing\Exception\MissingMandatoryParametersException When route has some missing mandatory parameters
  80. * @throws Symfony\Component\Routing\Exception\InvalidParameterException When a parameter value is not correct
  81. */
  82. protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute)
  83. {
  84. $variables = array_flip($variables);
  85. $originParameters = $parameters;
  86. $parameters = array_replace($this->context->getParameters(), $parameters);
  87. $tparams = array_replace($defaults, $parameters);
  88. // all params must be given
  89. if ($diff = array_diff_key($variables, $tparams)) {
  90. throw new MissingMandatoryParametersException(sprintf('The "%s" route has some missing mandatory parameters ("%s").', $name, implode('", "', array_keys($diff))));
  91. }
  92. $url = '';
  93. $optional = true;
  94. foreach ($tokens as $token) {
  95. if ('variable' === $token[0]) {
  96. if (false === $optional || !array_key_exists($token[3], $defaults) || (isset($parameters[$token[3]]) && $parameters[$token[3]] != $defaults[$token[3]])) {
  97. if (!$isEmpty = in_array($tparams[$token[3]], array(null, '', false), true)) {
  98. // check requirement
  99. if ($tparams[$token[3]] && !preg_match('#^'.$token[2].'$#', $tparams[$token[3]])) {
  100. throw new InvalidParameterException(sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $token[2], $tparams[$token[3]]));
  101. }
  102. }
  103. if (!$isEmpty || !$optional) {
  104. // %2F is not valid in a URL, so we don't encode it (which is fine as the requirements explicitly allowed it)
  105. $url = $token[1].str_replace('%2F', '/', rawurlencode($tparams[$token[3]])).$url;
  106. }
  107. $optional = false;
  108. }
  109. } elseif ('text' === $token[0]) {
  110. $url = $token[1].$url;
  111. $optional = false;
  112. }
  113. }
  114. if (!$url) {
  115. $url = '/';
  116. }
  117. // add a query string if needed
  118. if ($extra = array_diff_key($originParameters, $variables, $defaults)) {
  119. $url .= '?'.http_build_query($extra);
  120. }
  121. $url = $this->context->getBaseUrl().$url;
  122. if ($this->context->getHost()) {
  123. $scheme = $this->context->getScheme();
  124. if (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme != $req) {
  125. $absolute = true;
  126. $scheme = $req;
  127. }
  128. if ($absolute) {
  129. $port = '';
  130. if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
  131. $port = ':'.$this->context->getHttpPort();
  132. } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
  133. $port = ':'.$this->context->getHttpsPort();
  134. }
  135. $url = $scheme.'://'.$this->context->getHost().$port.$url;
  136. }
  137. }
  138. return $url;
  139. }
  140. }