public function replaceLangInUrl($url, $lang = null)
{
$parsed = parse_url($url);
$result = '';
if (isset($parsed['scheme'])) {
$result .= $parsed['scheme'] . '://';
}
if (isset($parsed['user'])) {
$result .= $parsed['user'];
if (isset($parsed['pass'])) {
$result .= ':' . $parsed['pass'];
}
$result .= '@';
}
if (isset($parsed['host'])) {
$result .= $parsed['host'] . '/';
}
if ('path' === $this->urlFormat && isset($parsed['path'])) {
$path = trim($parsed['path'], '/');
$replaced = preg_replace('#^(' . implode('|', $this->_languages) . '){1}#', $lang, $path);
$replaced = trim($replaced, '/');
if ($path === $replaced && null !== $lang) {
$replaced = $lang;
if ($path !== '') {
$replaced .= '/' . $path;
}
}
$result .= $replaced;
if ($result !== '') {
if (strpos($url, '/') === 0) {
$result = '/' . $result;
}
if (substr($url, -1) === '/') {
$result .= '/';
}
}
}
if ('get' === $this->urlFormat) {
$queryParams = [];
if (isset($parsed['query'])) {
parse_str($parsed['query'], $queryParams);
}
if (null === $lang && isset($queryParams[$this->langParam])) {
unset($queryParams[$this->langParam]);
} else {
$queryParams[$this->langParam] = $lang;
}
$query = urldecode(http_build_query($queryParams));
if ($query !== '') {
$result .= '?' . $query;
}
}
if ($result === '') {
$result .= '/';
}
return $result;
}