Generate absolute URL with specific scheme in Symfony2
Best way to go with this
$url = 'https:'.$this->generateUrl($routeName, $parameters, UrlGeneratorInterface::NETWORK_PATH)
According to the code or documentation, currently you cannot do that within the generateUrl method. So your "hackish" solution is still the best, but as @RaymondNijland commented you are better off with str_replace
:
$url = str_replace('http:', 'https:', $this->generateUrl($routeName, $parameters));
If you want to make sure it's changed only at the beginning of the string, you can write:
$url = preg_replace('/^http:/', 'https:', $this->generateUrl($routeName, $parameters));
No, the colon (:
) has no special meaning in the regex so you don't have to escape it.
With default UrlGenerator
, I don't think that is possible, if you don't want to mess with strings.
You could make your own HttpsUrlGenerator extends UrlGenerator
introducting one slight change:
Within method generate()
, instead of:
return $this->doGenerate(
$compiledRoute->getVariables(),
$route->getDefaults(),
$route->getRequirements(),
$compiledRoute->getTokens(),
$parameters,
$name,
$referenceType,
$compiledRoute->getHostTokens(),
$route->getSchemes()
);
You could do:
return $this->doGenerate(
$compiledRoute->getVariables(),
$route->getDefaults(),
$route->getRequirements(),
$compiledRoute->getTokens(),
$parameters,
$name,
$referenceType,
$compiledRoute->getHostTokens(),
['https']
);
As you can see, $route->getSchemes()
gets pumped into doGenerate()
based on the route settings (the tutorial link you provided above).
You could even go further and externalize this schema array and supply it via __construct
.
Hope this helps a bit ;)