1
0
mirror of https://gitnet.fr/deblan/gist.git synced 2021-08-14 08:30:49 +02:00
GIST/app/bootstrap.php.d/30-trans.php

76 lines
2.3 KiB
PHP
Raw Permalink Normal View History

2015-05-05 20:33:05 +02:00
<?php
use Silex\Provider\TranslationServiceProvider;
use Symfony\Component\HttpFoundation\AcceptHeader;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Translation\Loader\YamlFileLoader;
2015-11-23 20:47:45 +01:00
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
2015-05-05 20:33:05 +02:00
$app->register(new TranslationServiceProvider(), array(
'locale' => 'en',
'locale_fallback' => 'en',
2018-04-12 09:19:12 +02:00
'locales' => array('en', 'fr', 'es', 'de', 'cn', 'pl'),
2015-05-05 20:33:05 +02:00
));
$app['translator'] = $app->extend('translator', function ($translator, $app) {
$translator->addLoader('yaml', new YamlFileLoader());
foreach ($app['locales'] as $locale) {
$file = $app['root_path'].'/app/locales/'.$locale.'.yml';
if (is_file($file)) {
$translator->addResource('yaml', $file, $locale);
}
}
return $translator;
});
2015-05-06 00:18:16 +02:00
$app['routes'] = $app->share($app->extend('routes', function ($routes, $app) {
2015-05-05 20:33:05 +02:00
$routes->addPrefix('/{_locale}');
$routes->addDefaults(array('_locale' => $app['locale_fallbacks'][0]));
$routes->addRequirements(array('_locale' => implode('|', $app['locales'])));
return $routes;
2015-05-06 00:18:16 +02:00
}));
2015-05-05 20:33:05 +02:00
/**
* Redirect home on right locale page, regarding of request accept locale or
* default fallback.
*/
$app->get('/', function (Request $request) use ($app) {
$accept = AcceptHeader::fromString($request->headers->get('Accept-Language'));
2015-11-24 18:57:06 +01:00
$cookieValue = $request->cookies->get('locale');
2015-05-05 20:33:05 +02:00
2015-11-24 18:57:06 +01:00
if (!empty($cookieValue) && in_array($cookieValue, $app['locales'])) {
$foundLocale = $cookieValue;
2015-11-23 20:47:45 +01:00
} else {
$foundLocale = $app['translator']->getLocale();
2015-05-05 20:33:05 +02:00
2015-11-23 20:47:45 +01:00
foreach ($app['locales'] as $locale) {
2017-08-11 10:57:57 +02:00
if ($cookieValue === $locale || $accept->has($locale)) {
2015-11-23 20:47:45 +01:00
$foundLocale = $locale;
break;
}
2015-05-05 20:33:05 +02:00
}
}
return new RedirectResponse($app['url_generator']->generate(
'home',
array('_locale' => $foundLocale)
));
});
2015-11-23 20:47:45 +01:00
2015-11-24 19:02:40 +01:00
$app->after(function (Request $request, Response $response) use ($app) {
if ($response instanceof RedirectResponse) {
return;
}
$value = $request->get('_locale');
2015-11-24 18:57:06 +01:00
$cookie = new Cookie('locale', $value, strtotime('+1 month'));
2015-11-24 19:02:40 +01:00
$response->headers->setCookie($cookie);
2015-11-23 20:47:45 +01:00
});