diff options
Diffstat (limited to 'app/frontend/i18n')
-rw-r--r-- | app/frontend/i18n/Globalization.php | 77 | ||||
-rw-r--r-- | app/frontend/i18n/config.xml | 6 |
2 files changed, 81 insertions, 2 deletions
diff --git a/app/frontend/i18n/Globalization.php b/app/frontend/i18n/Globalization.php new file mode 100644 index 0000000..5c0b25a --- /dev/null +++ b/app/frontend/i18n/Globalization.php @@ -0,0 +1,77 @@ +<?php + +Prado::using('System.I18N.TGlobalization'); +Prado::using('System.I18N.core.HTTPNegotiator'); +Prado::using('Application.user.DbUser'); +Prado::using('Application.facades.UserFacade'); +Prado::using('Application.dto.LanguageDTO'); + +class Globalization extends TGlobalization { + + public function init($config) { + parent::init($config); + $this->getApplication()->attachEventHandler( + 'OnAuthenticationComplete', + [$this, 'setUserCulture'] + ); + } + + public function setUserCulture() { + $culture = $this->_getUserCulture($this->getUser()) + ?: $this->_autodetectCulture(); + Locale::setDefault($culture); + $this->setCulture($culture); + } + + protected function _getUserCulture(DbUser $user) { + if (!$user->IsGuest) { + $preference = UserFacade::getInstance()->getLanguagePreference($user); + if ($preference) { + $preference = $preference->Name; + } + if (!in_array($preference, $this->AllowedCultures)) { + $preference = $this->_getNeutralCulture($this->DefaultCulture); + } + return $preference; + } + return NULL; + } + + protected function _autodetectCulture() { + $culture = $this->_getNeutralCulture($this->DefaultCulture); + $http = new HTTPNegotiator(); + foreach ($http->getLanguages() as $language) { + $language = $this->_getNeutralCulture($language); + if (in_array($language, $this->AllowedCultures)) { + $culture = $language; + break; + } + } + return $culture; + } + + private function _getNeutralCulture($culture) { + return explode('_', $culture)[0]; + } + + public function getCulture() { + return $this->_getNeutralCulture(parent::getCulture()); + } + + public function setCulture($culture) { + parent::setCulture($this->_getNeutralCulture($culture)); + } + + protected $_allowedCultures = []; + + public function setAllowedCultures($cultures) { + $this->_allowedCultures = array_map('trim', explode(',', $cultures)); + } + + public function getAllowedCultures() { + return $this->_allowedCultures; + } + +} + +?> diff --git a/app/frontend/i18n/config.xml b/app/frontend/i18n/config.xml index c80b46d..52f5b7e 100644 --- a/app/frontend/i18n/config.xml +++ b/app/frontend/i18n/config.xml @@ -4,10 +4,12 @@ <using namespace="System.I18N.*" /> </paths> <modules> - <module id="globalization" class="System.I18N.TGlobalization"> + <module id="globalization" + class="Application.i18n.Globalization" + DefaultCulture="pl" + AllowedCultures="pl,en"> <translation type="gettext" source="Application.i18n" - autosave="true" cache="true" /> </module> </modules> |