Last active
March 4, 2021 03:25
-
-
Save spolischook/8c21f0fc8d39c17e4584 to your computer and use it in GitHub Desktop.
Set prefer language by parsing HTTP_ACCEPT_LANGUAGE header in Silex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 line8
to make it work properly.