1
0
mirror of https://gitnet.fr/deblan/gist.git synced 2021-08-14 08:30:49 +02:00

Default locale

This commit is contained in:
Simon Vieille 2015-11-23 20:47:45 +01:00
parent a6f20de8cf
commit c0eadc3433

View File

@ -5,6 +5,8 @@ use Symfony\Component\HttpFoundation\AcceptHeader;
use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\Loader\YamlFileLoader; use Symfony\Component\Translation\Loader\YamlFileLoader;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
$app->register(new TranslationServiceProvider(), array( $app->register(new TranslationServiceProvider(), array(
'locale' => 'en', 'locale' => 'en',
@ -40,19 +42,29 @@ $app['routes'] = $app->share($app->extend('routes', function ($routes, $app) {
*/ */
$app->get('/', function (Request $request) use ($app) { $app->get('/', function (Request $request) use ($app) {
$accept = AcceptHeader::fromString($request->headers->get('Accept-Language')); $accept = AcceptHeader::fromString($request->headers->get('Accept-Language'));
$cookie = $request->cookies->get('locale');
// Default locale fallback
if (!empty($cookie) && in_array($cookie, $app['locales'])) {
$foundLocale = $cookie;
} else {
$foundLocale = $app['translator']->getLocale(); $foundLocale = $app['translator']->getLocale();
foreach ($app['locales'] as $locale) { foreach ($app['locales'] as $locale) {
if ($accept->has($locale)) { if ($cookie === $locale || $accept->has($locale)) {
$foundLocale = $locale; $foundLocale = $locale;
break; break;
} }
} }
}
return new RedirectResponse($app['url_generator']->generate( return new RedirectResponse($app['url_generator']->generate(
'home', 'home',
array('_locale' => $foundLocale) array('_locale' => $foundLocale)
)); ));
}); });
$app->after(function(Request $request, Response $response) use ($app) {
$cookie = new Cookie('locale', $request->attributes->get('_locale'), strtotime('+1 month'));
$response->headers->setCookie($cookie);
});