Completed
Push — master ( cfc16f...6c07bb )
by Daniel
03:06
created

CommonLibLocale::setNumberFormat()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 1
eloc 6
nc 1
nop 2
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\common_lib;
30
31
/**
32
 * Usefull functions to support multi-language feedback
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait CommonLibLocale
37
{
38
39
    protected $commonLibFlags   = null;
40
    protected $tCmnLb           = null;
41
    protected $tCmnRequest      = null;
42
    protected $tCmnSession      = null;
43
    protected $tCmnSuperGlobals = null;
44
45
    private function getCommonLocaleFolder()
46
    {
47
        $pathes     = explode(DIRECTORY_SEPARATOR, __DIR__);
48
        $pathDepth  = count($pathes);
49
        $localePath = [];
50
        foreach ($pathes as $key => $value) {
51
            if ($key < ($pathDepth - 1)) {
52
                $localePath[] = $value;
53
            }
54
        }
55
        return implode(DIRECTORY_SEPARATOR, $localePath);
56
    }
57
58
    /**
59
     * Stores given language or default one into global session variable
60
     * (In order to avoid potential language injections from other applications session will revert
61
     * to the default language if application one is not among the one are not supported here)
62
     *
63
     * @return NOTHING
64
     */
65
    private function handleLanguageIntoSession()
66
    {
67
        $this->settingsCommonLib();
68
        $this->initializeSprGlbAndSession();
69
        if (is_null($this->tCmnSuperGlobals->get('lang'))) {
70
            $this->tCmnSession->set('lang', $this->commonLibFlags['default_language']);
71
        } elseif (!is_null($this->tCmnSuperGlobals->get('lang'))) {
72
            $this->tCmnSession->set('lang', filter_var($this->tCmnSuperGlobals->get('lang'), FILTER_SANITIZE_STRING));
73
        }
74
        if (!array_key_exists($this->tCmnSession->get('lang'), $this->commonLibFlags['available_languages'])) {
75
            $this->tCmnSession->set('lang', $this->commonLibFlags['default_language']);
76
        }
77
    }
78
79
    /**
80
     * Takes care of instatiation of localization libraries
81
     * used within current module for multi-languages support
82
     *
83
     * @return NOTHING
84
     */
85
    private function handleLocalizationCommon()
86
    {
87
        $this->handleLanguageIntoSession();
88
        $localizationFile = $this->getCommonLocaleFolder() . '/locale/'
89
                . $this->tCmnSuperGlobals->get('lang') . '/LC_MESSAGES/'
90
                . $this->commonLibFlags['localization_domain']
91
                . '.mo';
92
        $extrClass        = new \Gettext\Extractors\Mo();
93
        $translations     = $extrClass->fromFile($localizationFile);
94
        $this->tCmnLb     = new \Gettext\Translator();
95
        $this->tCmnLb->loadTranslations($translations);
96
    }
97
98
    protected function initializeSprGlbAndSession()
99
    {
100
        if (is_null($this->tCmnSuperGlobals)) {
101
            $this->tCmnRequest      = new \Symfony\Component\HttpFoundation\Request;
102
            $this->tCmnSuperGlobals = $this->tCmnRequest->createFromGlobals();
103
        }
104
        if (is_null($this->tCmnSession)) {
105
            $sBridge           = new \Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage();
106
            $this->tCmnSession = new \Symfony\Component\HttpFoundation\Session\Session($sBridge);
107
            $this->tCmnSession->start();
108
        }
109
    }
110
111
    /**
112
     * Central function to deal with multi-language messages
113
     *
114
     * @param string $localizedStringCode
115
     * @return string
116
     */
117
    protected function lclMsgCmn($localizedStringCode)
118
    {
119
        if (is_null($this->commonLibFlags)) {
120
            $this->settingsCommonLib();
121
            $this->handleLocalizationCommon();
122
        }
123
        return $this->tCmnLb->gettext($localizedStringCode);
124
    }
125
126
    protected function lclMsgCmnNumber($singularString, $pluralString, $numberToEvaluate)
127
    {
128
        if (is_null($this->commonLibFlags)) {
129
            $this->settingsCommonLib();
130
            $this->handleLocalizationCommon();
131
        }
132
        return $this->tCmnLb->ngettext($singularString, $pluralString, $numberToEvaluate);
133
    }
134
135
    protected function setNumberFormat($content, $features = null)
136
    {
137
        $features = $this->setNumberFormatFeatures($features);
138
        $fmt      = new \NumberFormatter($features['locale'], $features['style']);
139
        $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $features['MinFractionDigits']);
140
        $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $features['MaxFractionDigits']);
141
        return $fmt->format($content);
142
    }
143
144
    private function setNumberFormatFeatures($features)
145
    {
146
        $this->handleLanguageIntoSession();
147
        if (is_null($features)) {
148
            $features = [
149
                'locale'            => $this->tCmnSession->get('lang'),
150
                'style'             => \NumberFormatter::DECIMAL,
151
                'MinFractionDigits' => 0,
152
                'MaxFractionDigits' => 0,
153
            ];
154
        }
155
        if (!array_key_exists('locale', $features)) {
156
            $features['locale'] = $this->tCmnSession->get('lang');
157
        }
158
        if (!array_key_exists('style', $features)) {
159
            $features['style'] = \NumberFormatter::DECIMAL;
160
        }
161
        return $features;
162
    }
163
164
    /**
165
     * Settings
166
     *
167
     * @return NOTHING
168
     */
169
    private function settingsCommonLib()
170
    {
171
        $this->commonLibFlags = [
172
            'available_languages' => [
173
                'en_US' => 'US English',
174
                'ro_RO' => 'Română',
175
                'it_IT' => 'Italiano',
176
            ],
177
            'default_language'    => 'en_US',
178
            'localization_domain' => 'common-locale'
179
        ];
180
    }
181
}
182