Create an absolute url with custom schema in symfony2

I want to create an absolute URL with a specific scheme (https) in a Symfony2 controller. All the solutions that I found point me to configure the target route so that it requires this scheme . But I need a route so that it remains available in http, so I can’t configure it to require https (in this case, HTTP requests are redirected to the corresponding https address).

Is there a way to generate a URL, within just this URL generation, a specific scheme?

I have seen that using the 'network' keyword generates a “network path" URL that looks like "//example.com/dir/file"; so maybe i can just do

 'https:' . $this->generateUrl($routeName, $parameters, 'network') 

But I don't know if this will be robust enough for any route or request context.

UPDATE: after examining the URL generation code, this way of getting around the “network path” seems completely reliable. The network path is generated exactly as an absolute URL, with no scheme up to "//".

+7
php symfony
source share
3 answers

According to the code or documentation, you cannot currently do this in the generateUrl method. Thus, your “hacker" solution is still the best, but as @RaymondNijland said, you are better off with str_replace :

 $url = str_replace('http:', 'https:', $this->generateUrl($routeName, $parameters)); 

If you want to make sure that only one occurrence is replaced, you can write:

 $url = str_replace('http:', 'https:', $this->generateUrl($routeName, $parameters), 1); 

If you want to make sure that it changes only at the beginning of the line, you can write:

 $url = preg_replace('/^http:/', 'https:', $this->generateUrl($routeName, $parameters)); 

No, a colon ( : does not really matter in a regular expression, so you don't need to avoid it.

+3
source share

Best way to go with this

 $url = 'https:'.$this->generateUrl($routeName, $parameters, UrlGeneratorInterface::NETWORK_PATH) 
+3
source share

By default, UrlGenerator , I do not think this is possible if you do not want to bind to strings.

You can make your own HttpsUrlGenerator extends UrlGenerator introducing one small change:

Inside the generate() method instead:

 return $this->doGenerate( $compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes() ); 

You can do:

 return $this->doGenerate( $compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), ['https'] ); 

As you can see, $route->getSchemes() loaded into doGenerate() based on the route settings (link to the tutorial above).

You can even go further and externalize this array of circuits and provide it via __construct .

Hope this helps a bit;)

+2
source share

All Articles