Skip to content

Instantly share code, notes, and snippets.

@hmic
Created February 22, 2016 18:39
Show Gist options
  • Save hmic/cd83d86c07c8ea2c030b to your computer and use it in GitHub Desktop.
Save hmic/cd83d86c07c8ea2c030b to your computer and use it in GitHub Desktop.
<?php
namespace App;
use Cake\Event\Event;
use Cake\I18n\I18n;
use Cake\Routing\DispatcherFilter;
use Locale;
class LocaleSessionFilter extends DispatcherFilter
{
protected $_locales = [];
public function __construct($config = [])
{
parent::__construct($config);
if (!empty($config['locales'])) {
$this->_locales = $config['locales'];
}
}
public function beforeDispatch(Event $event)
{
$request = $event->data['request'];
$locale = Locale::acceptFromHttp($request->header('Accept-Language'));
$language = $request->session()->read('Config.language');
if(!$language || !in_array($language, $this->_locales)) {
if($locale && in_array($locale, $this->_locales)) {
$language = $locale;
}
}
if($language && in_array($language, $this->_locales)) {
$locale = $language;
} else {
$language = $locale = 'en_EN';
}
$request->session()->write('Config.language', $language);
I18n::locale($language);
}
}
// in your bootstrap.php add:
DispatcherFactory::add('App\LocaleSessionFilter', ['locales' => ['de_DE', 'en_EN']]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment