Detecta el idioma y redirige al subdominio en Symfony
Estoy usando Symfony 1.2.7. Mi web está en varios idiomas, cada uno de ellos está en un subdominio como en.example.com, es.example.com. Si el usuario ingresa a example.com, quiero redirigirlo a su idioma. También quiero tener soporte staging.example.com y redirigir a es.staging.example.com y en.staging.example.com para poder probar todo antes de la implementación.
Tengo el siguiente código que funciona tanto en index.php como en frontend_dev.php. Mi pregunta es, ¿puedes mejorarlo? ¿Hay una manera mejor o más limpia? ¡Gracias!
require_once(dirname(__FILE__).'/../config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'dev', true);
$context = sfContext::createInstance($configuration);
// get the domain parts as an array
$host = array_reverse(explode('.', $_SERVER['HTTP_HOST']));
list($tld, $domain, $subdomain) = $host;
// determine which subdomain we're looking at
$app = ($subdomain == 'staging') ? $subdomain2=$host[3] : $subdomain;
if(empty($app) || $app == 'www')
{
$browser_languages = $context->getRequest()->getLanguages();
foreach($browser_languages as $language)
{
$allowed_culture = in_array($language, sfConfig::get('app_languagesAvailable'));
if($allowed_culture)
{
$domain = $subdomain ? $subdomain.'.'.$domain : $domain;
$url = 'http://'.str_replace($domain.'.'.$tld, $language.'.'.$domain.'.'.$tld, $_SERVER['HTTP_HOST']).$_SERVER['REQUEST_URI'];
$context->getController()->redirect($url);
break;
}
}
}
$context->dispatch();
Actualizar Solución: filtro personalizado
<?php
class subdomainFilter extends sfFilter
{
public function execute($filterChain)
{
$context = $this->getContext();
$user = $this->getContext()->getUser();
$request = $this->getContext()->getRequest();
// get the domain parts as an array
$host = array_reverse(explode('.', $request->getHost()));
list($tld, $domain) = $host;
$subdomain2 = $host[3];
$subdomain = $host[2];
// determine which subdomain we're looking at
$app = ($host[2] == 'staging') ? $subdomain2 : $subdomain;
if(empty($app) || $app == 'www')
{
// if first time
if ($this->isFirstCall())
{
$browser_languages = $request->getLanguages();
// set default lang, for API as CURL doesn't set the language
$lang = sfConfig::get('app_default_culture');
foreach($browser_languages as $language)
{
$allowed_culture = in_array($language, sfConfig::get('app_languagesAvailable'));
if($allowed_culture)
{
$lang = $language;
break;
}
}
}else {
// Get user culture
$lang = $user->getCulture();
}
$domain = $subdomain ? $subdomain.'.'.$domain : $domain;
$url = str_replace($domain.'.'.$tld, $lang.'.'.$domain.'.'.$tld, $request->getURI());
$context->getController()->redirect($url);
}
$filterChain->execute();
}
}