summaryrefslogtreecommitdiff
path: root/app/frontend/i18n/Globalization.php
blob: 25294ce441122f8de8b7b81418ba5e3eb515786d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
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(string $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(string $cultures) {
        $this->_allowedCultures = array_map('trim', explode(',', $cultures));
    }

    public function getAllowedCultures() {
        return $this->_allowedCultures;
    }

}

?>