Contao\CoreBundle\Routing\UrlGenerator::generate PHP Method

generate() public method

Generates a Contao URL.
public generate ( string $name, array $parameters = [], integer $referenceType = self::ABSOLUTE_PATH ) : string
$name string
$parameters array
$referenceType integer
return string
    public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH)
    {
        $this->framework->initialize();
        if (!is_array($parameters)) {
            $parameters = [];
        }
        $context = $this->getContext();
        // Store the original request context
        $host = $context->getHost();
        $scheme = $context->getScheme();
        $httpPort = $context->getHttpPort();
        $httpsPort = $context->getHttpsPort();
        $this->prepareLocale($parameters);
        $this->prepareAlias($name, $parameters);
        $this->prepareDomain($context, $parameters, $referenceType);
        $url = $this->router->generate('index' === $name ? 'contao_index' : 'contao_frontend', $parameters, $referenceType);
        // Reset the request context
        $context->setHost($host);
        $context->setScheme($scheme);
        $context->setHttpPort($httpPort);
        $context->setHttpsPort($httpsPort);
        return $url;
    }

Usage Example

 /**
  * Tests that the context is not modified if the hostname is set.
  *
  * To tests this case, we omit the _ssl parameter and set the scheme to "https" in the context. If the
  * generator still returns a HTTPS URL, we know that the context has not been modified.
  */
 public function testContextNotModifiedIfHostnameIsSet()
 {
     $routes = new RouteCollection();
     $routes->add('contao_index', new Route('/'));
     $context = new RequestContext();
     $context->setHost('contao.org');
     $context->setScheme('https');
     $generator = new UrlGenerator(new ParentUrlGenerator($routes, $context), $this->mockContaoFramework(), false);
     $this->assertEquals('https://contao.org/', $generator->generate('index', ['_domain' => 'contao.org'], UrlGeneratorInterface::ABSOLUTE_URL));
 }