cybtow cybtow - 3 months ago 35
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());
})->bind('homepage');


Before middleware:

// i18n Control
$locale = $request->getLocale();
$allowLocale = ['en','es','de'];
if (!in_array($locale, $allowLocale)) {
$request->setLocale('en');
$response = new \Symfony\Component\HttpFoundation\RedirectResponse($app['url_generator']->generate('homepage'), 301);
$response->prepare($request);
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.

Thanks.

Answer

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'])) {

    $request->setLocale($app['defaultLanguage']);
    $app['translator']->setLocale($app['defaultLanguage']);

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