Completed
Push — master ( 655942...648884 )
by Daniel
02:59
created

CommonLibLocale::handleLanguageIntoSession()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
c 5
b 0
f 0
dl 0
loc 11
rs 9.2
cc 4
eloc 8
nc 3
nop 0
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
    private function getTimestampArray($crtTime)
59
    {
60
        return ['float' => $this->getTimestampFloat($crtTime), 'string' => $this->getTimestampString($crtTime)];
61
    }
62
63
    private function getTimestampFloat($crtTime)
64
    {
65
        return ($crtTime['sec'] + $crtTime['usec'] / pow(10, 6));
66
    }
67
68
    protected function getTimestampRaw($returnType)
69
    {
70
        return call_user_func([$this, 'getTimestamp' . ucfirst($returnType)], gettimeofday());
71
    }
72
73
    private function getTimestampString($crtTime)
74
    {
75
        return implode('', [
76
            '<span style="color:black!important;font-weight:bold;">[',
77
            date('Y-m-d H:i:s.', $crtTime['sec']),
78
            substr(round($crtTime['usec'], -3), 0, 3),
79
            ']</span> '
80
        ]);
81
    }
82
83
    /**
84
     * Stores given language or default one into global session variable
85
     * (In order to avoid potential language injections from other applications session will revert
86
     * to the default language if application one is not among the one are not supported here)
87
     *
88
     * @return NOTHING
89
     */
90
    private function handleLanguageIntoSession()
91
    {
92
        $this->settingsCommonLib();
93
        $this->initializeSprGlbAndSession();
94
        if (is_null($this->tCmnSuperGlobals->get('lang')) && is_null($this->tCmnSession->get('lang'))) {
95
            $this->tCmnSession->set('lang', $this->commonLibFlags['default_language']);
96
        } elseif (!is_null($this->tCmnSuperGlobals->get('lang'))) {
97
            $this->tCmnSession->set('lang', filter_var($this->tCmnSuperGlobals->get('lang'), FILTER_SANITIZE_STRING));
98
        }
99
        $this->normalizeLocalizationIntoSession();
100
    }
101
102
    /**
103
     * Takes care of instatiation of localization libraries
104
     * used within current module for multi-languages support
105
     *
106
     * @return NOTHING
107
     */
108
    private function handleLocalizationCommon()
109
    {
110
        $this->handleLanguageIntoSession();
111
        $localizationFile = $this->getCommonLocaleFolder() . '/locale/'
112
                . $this->tCmnSession->get('lang') . '/LC_MESSAGES/'
113
                . $this->commonLibFlags['localization_domain']
114
                . '.mo';
115
        $extrClass        = new \Gettext\Extractors\Mo();
116
        $translations     = $extrClass->fromFile($localizationFile);
117
        $this->tCmnLb     = new \Gettext\Translator();
118
        $this->tCmnLb->loadTranslations($translations);
119
    }
120
121
    protected function initializeSprGlbAndSession()
122
    {
123
        if (is_null($this->tCmnSuperGlobals)) {
124
            $this->tCmnRequest      = new \Symfony\Component\HttpFoundation\Request;
125
            $this->tCmnSuperGlobals = $this->tCmnRequest->createFromGlobals();
126
        }
127
        if (is_null($this->tCmnSession)) {
128
            $sBridge           = new \Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage();
129
            $this->tCmnSession = new \Symfony\Component\HttpFoundation\Session\Session($sBridge);
130
            $this->tCmnSession->start();
131
        }
132
    }
133
134
    /**
135
     * Central function to deal with multi-language messages
136
     *
137
     * @param string $localizedStringCode
138
     * @return string
139
     */
140
    protected function lclMsgCmn($localizedStringCode)
141
    {
142
        if (is_null($this->tCmnLb)) {
143
            $this->settingsCommonLib();
144
            $this->handleLocalizationCommon();
145
        }
146
        return $this->tCmnLb->gettext($localizedStringCode);
147
    }
148
149
    protected function lclMsgCmnNumber($singularString, $pluralString, $numberToEvaluate)
150
    {
151
        if (is_null($this->tCmnLb)) {
152
            $this->settingsCommonLib();
153
            $this->handleLocalizationCommon();
154
        }
155
        return $this->tCmnLb->ngettext($singularString, $pluralString, $numberToEvaluate);
156
    }
157
158
    private function normalizeLocalizationIntoSession()
159
    {
160
        if (!array_key_exists($this->tCmnSession->get('lang'), $this->commonLibFlags['available_languages'])) {
161
            $this->tCmnSession->set('lang', $this->commonLibFlags['default_language']);
162
        }
163
    }
164
165
    /**
166
     * Returns proper result from a mathematical division in order to avoid
167
     * Zero division erorr or Infinite results
168
     *
169
     * @param float $fAbove
170
     * @param float $fBelow
171
     * @param mixed $mArguments
172
     * @return decimal
173
     */
174
    protected function setDividedResult($fAbove, $fBelow, $mArguments = 0)
175
    {
176
        if (($fAbove == 0) || ($fBelow == 0)) { // prevent infinite result AND division by 0
177
            return 0;
178
        }
179
        if (is_array($mArguments)) {
180
            $frMinMax = [
181
                'MinFractionDigits' => $mArguments[1],
182
                'MaxFractionDigits' => $mArguments[1],
183
            ];
184
            return $this->setNumberFormat(($fAbove / $fBelow), $frMinMax);
185
        }
186
        return $this->setNumberFormat(round(($fAbove / $fBelow), $mArguments));
187
    }
188
189
    protected function setNumberFormat($content, $features = null)
190
    {
191
        $features = $this->setNumberFormatFeatures($features);
192
        $fmt      = new \NumberFormatter($features['locale'], $features['style']);
193
        $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $features['MinFractionDigits']);
194
        $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $features['MaxFractionDigits']);
195
        return $fmt->format($content);
196
    }
197
198
    private function setNumberFormatFeatures($features)
199
    {
200
        $this->handleLanguageIntoSession();
201
        if (is_null($features)) {
202
            $features = [
203
                'locale'            => $this->tCmnSession->get('lang'),
204
                'style'             => \NumberFormatter::DECIMAL,
205
                'MinFractionDigits' => 0,
206
                'MaxFractionDigits' => 0,
207
            ];
208
        }
209
        if (!array_key_exists('locale', $features)) {
210
            $features['locale'] = $this->tCmnSession->get('lang');
211
        }
212
        if (!array_key_exists('style', $features)) {
213
            $features['style'] = \NumberFormatter::DECIMAL;
214
        }
215
        return $features;
216
    }
217
218
    /**
219
     * Settings
220
     *
221
     * @return NOTHING
222
     */
223
    private function settingsCommonLib()
224
    {
225
        $this->commonLibFlags = [
226
            'available_languages' => [
227
                'en_US' => 'US English',
228
                'ro_RO' => 'Română',
229
                'it_IT' => 'Italiano',
230
            ],
231
            'default_language'    => 'en_US',
232
            'localization_domain' => 'common-locale'
233
        ];
234
    }
235
}
236