Completed
Push — master ( 91b102...f00e62 )
by Daniel
06:22
created

CommonLibLocale   A

Complexity

Total Complexity 31

Size/Duplication

Total Lines 202
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 11
Bugs 0 Features 0
Metric Value
wmc 31
c 11
b 0
f 0
lcom 1
cbo 5
dl 0
loc 202
rs 9.8

16 Methods

Rating   Name   Duplication   Size   Complexity  
A getTimestampArray() 0 4 1
A getTimestampFloat() 0 4 1
A getTimestampRaw() 0 4 1
A getTimestampString() 0 9 1
A initializeSprGlbAndSession() 0 12 3
A handleLanguageIntoSession() 0 11 4
A handleLocalizationCommon() 0 12 1
A getCommonLocaleFolder() 0 12 3
A lclManagePrerequisites() 0 7 2
A lclMsgCmn() 0 5 1
A lclMsgCmnNumber() 0 5 1
A normalizeLocalizationIntoSession() 0 6 2
A setDividedResult() 0 14 4
A setNumberFormat() 0 8 1
A setNumberFormatFeatures() 0 19 4
A settingsCommonLib() 0 12 1
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
        $translations     = new \Gettext\Translations;
116
        $translations->addFromMoFile($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
    private function lclManagePrerequisites()
135
    {
136
        if (is_null($this->tCmnLb)) {
137
            $this->settingsCommonLib();
138
            $this->handleLocalizationCommon();
139
        }
140
    }
141
142
    /**
143
     * Central function to deal with multi-language messages
144
     *
145
     * @param string $localizedStringCode
146
     * @return string
147
     */
148
    protected function lclMsgCmn($localizedStringCode)
149
    {
150
        $this->lclManagePrerequisites();
151
        return $this->tCmnLb->gettext($localizedStringCode);
152
    }
153
154
    protected function lclMsgCmnNumber($singularString, $pluralString, $numberToEvaluate)
155
    {
156
        $this->lclManagePrerequisites();
157
        return sprintf($this->tCmnLb->ngettext($singularString, $pluralString, $numberToEvaluate), 1);
158
    }
159
160
    private function normalizeLocalizationIntoSession()
161
    {
162
        if (!array_key_exists($this->tCmnSession->get('lang'), $this->commonLibFlags['available_languages'])) {
163
            $this->tCmnSession->set('lang', $this->commonLibFlags['default_language']);
164
        }
165
    }
166
167
    /**
168
     * Returns proper result from a mathematical division in order to avoid
169
     * Zero division erorr or Infinite results
170
     *
171
     * @param float $fAbove
172
     * @param float $fBelow
173
     * @param mixed $mArguments
174
     * @return decimal
175
     */
176
    protected function setDividedResult($fAbove, $fBelow, $mArguments = null)
177
    {
178
        if (($fAbove == 0) || ($fBelow == 0)) { // prevent infinite result AND division by 0
179
            return 0;
180
        }
181
        if (is_numeric($mArguments)) {
182
            $frMinMax = [
183
                'MinFractionDigits' => $mArguments,
184
                'MaxFractionDigits' => $mArguments,
185
            ];
186
            return $this->setNumberFormat(($fAbove / $fBelow), $frMinMax);
187
        }
188
        return $this->setNumberFormat(round(($fAbove / $fBelow), $mArguments));
189
    }
190
191
    protected function setNumberFormat($content, $ftrs = null)
192
    {
193
        $features = $this->setNumberFormatFeatures($ftrs);
194
        $fmt      = new \NumberFormatter($features['locale'], $features['style']);
195
        $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $features['MinFractionDigits']);
196
        $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $features['MaxFractionDigits']);
197
        return $fmt->format($content);
198
    }
199
200
    private function setNumberFormatFeatures($features)
201
    {
202
        $this->handleLanguageIntoSession();
203
        if (is_null($features)) {
204
            $features = [
205
                'locale'            => $this->tCmnSession->get('lang'),
206
                'style'             => \NumberFormatter::DECIMAL,
207
                'MinFractionDigits' => 0,
208
                'MaxFractionDigits' => 0,
209
            ];
210
        }
211
        if (!array_key_exists('locale', $features)) {
212
            $features['locale'] = $this->tCmnSession->get('lang');
213
        }
214
        if (!array_key_exists('style', $features)) {
215
            $features['style'] = \NumberFormatter::DECIMAL;
216
        }
217
        return $features;
218
    }
219
220
    /**
221
     * Settings
222
     *
223
     * @return NOTHING
224
     */
225
    private function settingsCommonLib()
226
    {
227
        $this->commonLibFlags = [
228
            'available_languages' => [
229
                'en_US' => 'US English',
230
                'ro_RO' => 'Română',
231
                'it_IT' => 'Italiano',
232
            ],
233
            'default_language'    => 'en_US',
234
            'localization_domain' => 'common-locale'
235
        ];
236
    }
237
}
238