cybtow cybtow - 8 months ago 76
PHP Question

Silex redirect changing the locale

I am using Silex 2 and I would like to redirect to homepage with default locale if any url is loaded using an invalid locale.

// homepage / root
$this->get('{_locale}/', function (Request $request) use ($app) {
return $app['twig']->render('index/index.html.twig', array());

Before middleware:

// i18n Control
$locale = $request->getLocale();
$allowLocale = ['en','es','de'];
if (!in_array($locale, $allowLocale)) {
$response = new \Symfony\Component\HttpFoundation\RedirectResponse($app['url_generator']->generate('homepage'), 301);
return $response->send();

But this code produces an infinite loop.

I want:

If user insert this URL: /es/foo then all is ok.

If user insert this URL: /fr/foo then he must be redirect to /en.



You can do the same, but easily as you can pass the URL parameter to the url_generator service. Also to make your app more flexible and less error prone, you should embarace the container for global configurations (for allowedLocales and defaultLanguage):

// somewhere in your configuration
$app['defaultLanguage'] = 'en';
$app['allowedLocales'] = ['en','es','de']

// Then in your controller
$locale = $request->getLocale();
if (!in_array($locale, $app['allowLocales'])) {


    return $app->redirect(
        $app['url_generator']->generate('homepage', ["locale" => $app['defaultLanguage']]),