Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spolischook/8c21f0fc8d39c17e4584 to your computer and use it in GitHub Desktop.
Save spolischook/8c21f0fc8d39c17e4584 to your computer and use it in GitHub Desktop.
Set prefer language by parsing HTTP_ACCEPT_LANGUAGE header in Silex
<?php
$app->register(new Silex\Provider\TranslationServiceProvider(), [
'locale_fallbacks' => ['en', 'uk', 'ru'],
]);
$app->before(function() use ($app) {
$locales = $app['translator']->getFallbackLocales();
$prefLocales = array_reduce(explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']), function ($res, $el) { list($l, $q) = array_merge(explode(';q=', $el), [1]); $res[$l] = (float) $q; return $res; }, []);
asort($prefLocales);
$locale = array_reduce(array_keys($prefLocales), function ($default, $prefLocale) use ($locales) { return in_array($prefLocale, $locales) ? $prefLocale : $default; }, $app['translator']->getLocale());
$app['translator']->setLocale($locale);
});
$app->get('/', function (\Symfony\Component\HttpFoundation\Request $request) use ($app) {
return $app->redirect('/'.$app['translator']->getLocale());
});
$app->get('/{_locale}', function () use ($app) {
return $app['twig']->render('index.html.twig');
});
@TomaszKotlarek
Copy link

I'm not sure if this comment is the right place to report an issue, but I had to change $res[$l] to $res[trim($l)] in line 8 to make it work properly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment