This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Component/Routing/Generator/UrlGenerator.php

173 lines
5.8 KiB
PHP
Raw Normal View History

2010-02-17 13:53:31 +00:00
<?php
/*
* This file is part of the Symfony package.
2010-02-17 13:53:31 +00:00
*
* (c) Fabien Potencier <fabien@symfony.com>
2010-02-17 13:53:31 +00:00
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
2010-02-17 13:53:31 +00:00
*/
namespace Symfony\Component\Routing\Generator;
use Symfony\Component\Routing\Route;
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\RequestContext;
use Symfony\Component\Routing\Exception\InvalidParameterException;
2011-05-17 15:51:56 +01:00
use Symfony\Component\Routing\Exception\RouteNotFoundException;
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
2010-02-17 13:53:31 +00:00
/**
* UrlGenerator generates URL based on a set of routes.
*
* @author Fabien Potencier <fabien@symfony.com>
2011-06-14 14:35:32 +01:00
*
* @api
2010-02-17 13:53:31 +00:00
*/
class UrlGenerator implements UrlGeneratorInterface
{
protected $context;
2011-03-23 18:24:18 +00:00
private $routes;
private $cache;
/**
* Constructor.
*
2011-04-23 16:05:44 +01:00
* @param RouteCollection $routes A RouteCollection instance
* @param RequestContext $context The context
2011-06-14 14:35:32 +01:00
*
* @api
*/
public function __construct(RouteCollection $routes, RequestContext $context)
2010-02-17 13:53:31 +00:00
{
$this->routes = $routes;
$this->context = $context;
$this->cache = array();
2010-02-17 13:53:31 +00:00
}
/**
* Sets the request context.
*
2011-04-23 16:05:44 +01:00
* @param RequestContext $context The context
2011-06-14 14:35:32 +01:00
*
* @api
*/
public function setContext(RequestContext $context)
{
$this->context = $context;
}
2011-04-21 20:20:27 +01:00
/**
* Gets the request context.
*
* @return RequestContext The context
*/
public function getContext()
{
return $this->context;
}
/**
* Generates a URL from the given parameters.
*
* @param string $name The name of the route
* @param array $parameters An array of parameters
* @param Boolean $absolute Whether to generate an absolute URL
*
* @return string The generated URL
*
2011-05-17 15:51:56 +01:00
* @throws Symfony\Component\Routing\Exception\RouteNotFoundException When route doesn't exist
2011-06-14 14:35:32 +01:00
*
* @api
*/
public function generate($name, array $parameters = array(), $absolute = false)
2010-02-17 13:53:31 +00:00
{
made some method name changes to have a better coherence throughout the framework When an object has a "main" many relation with related "things" (objects, parameters, ...), the method names are normalized: * get() * set() * all() * replace() * remove() * clear() * isEmpty() * add() * register() * count() * keys() The classes below follow this method naming convention: * BrowserKit\CookieJar -> Cookie * BrowserKit\History -> Request * Console\Application -> Command * Console\Application\Helper\HelperSet -> HelperInterface * DependencyInjection\Container -> services * DependencyInjection\ContainerBuilder -> services * DependencyInjection\ParameterBag\ParameterBag -> parameters * DependencyInjection\ParameterBag\FrozenParameterBag -> parameters * DomCrawler\Form -> FormField * EventDispatcher\Event -> parameters * Form\FieldGroup -> Field * HttpFoundation\HeaderBag -> headers * HttpFoundation\ParameterBag -> parameters * HttpFoundation\Session -> attributes * HttpKernel\Profiler\Profiler -> DataCollectorInterface * Routing\RouteCollection -> Route * Security\Authentication\AuthenticationProviderManager -> AuthenticationProviderInterface * Templating\Engine -> HelperInterface * Translation\MessageCatalogue -> messages The usage of these methods are only allowed when it is clear that there is a main relation: * a CookieJar has many Cookies; * a Container has many services and many parameters (as services is the main relation, we use the naming convention for this relation); * a Console Input has many arguments and many options. There is no "main" relation, and so the naming convention does not apply. For many relations where the convention does not apply, the following methods must be used instead (where XXX is the name of the related thing): * get() -> getXXX() * set() -> setXXX() * all() -> getXXXs() * replace() -> setXXXs() * remove() -> removeXXX() * clear() -> clearXXX() * isEmpty() -> isEmptyXXX() * add() -> addXXX() * register() -> registerXXX() * count() -> countXXX() * keys()
2010-11-23 08:42:19 +00:00
if (null === $route = $this->routes->get($name)) {
2011-05-17 15:51:56 +01:00
throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
}
2010-02-17 13:53:31 +00:00
if (!isset($this->cache[$name])) {
$this->cache[$name] = $route->compile();
}
2010-02-17 13:53:31 +00:00
return $this->doGenerate($this->cache[$name]->getVariables(), $route->getDefaults(), $route->getRequirements(), $this->cache[$name]->getTokens(), $parameters, $name, $absolute);
2010-02-17 13:53:31 +00:00
}
/**
* @throws Symfony\Component\Routing\Exception\MissingMandatoryParametersException When route has some missing mandatory parameters
* @throws Symfony\Component\Routing\Exception\InvalidParameterException When a parameter value is not correct
*/
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute)
2010-02-17 13:53:31 +00:00
{
2011-04-25 11:03:41 +01:00
$variables = array_flip($variables);
$originParameters = $parameters;
$parameters = array_replace($this->context->getParameters(), $parameters);
$tparams = array_replace($defaults, $parameters);
// all params must be given
if ($diff = array_diff_key($variables, $tparams)) {
2011-05-26 11:54:21 +01:00
throw new MissingMandatoryParametersException(sprintf('The "%s" route has some missing mandatory parameters ("%s").', $name, implode('", "', array_keys($diff))));
2010-02-17 13:53:31 +00:00
}
$url = '';
$optional = true;
foreach ($tokens as $token) {
if ('variable' === $token[0]) {
if (false === $optional || !array_key_exists($token[3], $defaults) || (isset($parameters[$token[3]]) && $parameters[$token[3]] != $defaults[$token[3]])) {
if (!$isEmpty = in_array($tparams[$token[3]], array(null, '', false), true)) {
// check requirement
if ($tparams[$token[3]] && !preg_match('#^'.$token[2].'$#', $tparams[$token[3]])) {
throw new InvalidParameterException(sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $token[2], $tparams[$token[3]]));
}
}
if (!$isEmpty || !$optional) {
// %2F is not valid in a URL, so we don't encode it (which is fine as the requirements explicitly allowed it)
$url = $token[1].str_replace('%2F', '/', rawurlencode($tparams[$token[3]])).$url;
}
$optional = false;
}
} elseif ('text' === $token[0]) {
2011-04-25 11:03:41 +01:00
$url = $token[1].$url;
$optional = false;
}
2010-02-17 13:53:31 +00:00
}
if (!$url) {
$url = '/';
}
2010-02-17 13:53:31 +00:00
// add a query string if needed
if ($extra = array_diff_key($originParameters, $variables, $defaults)) {
$url .= '?'.http_build_query($extra);
}
2010-02-17 13:53:31 +00:00
$url = $this->context->getBaseUrl().$url;
2010-02-17 13:53:31 +00:00
if ($this->context->getHost()) {
$scheme = $this->context->getScheme();
if (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme != $req) {
$absolute = true;
$scheme = $req;
}
if ($absolute) {
$port = '';
if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
$port = ':'.$this->context->getHttpPort();
} elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
$port = ':'.$this->context->getHttpsPort();
}
$url = $scheme.'://'.$this->context->getHost().$port.$url;
}
}
2010-02-17 13:53:31 +00:00
return $url;
}
2010-02-17 13:53:31 +00:00
}