Completed
Push — master ( 87b411...bbcb69 )
by Daniel
02:45
created

CommonLibLocale::getTimestampArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 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'))) {
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
        if (!array_key_exists($this->tCmnSession->get('lang'), $this->commonLibFlags['available_languages'])) {
100
            $this->tCmnSession->set('lang', $this->commonLibFlags['default_language']);
101
        }
102
    }
103
104
    /**
105
     * Takes care of instatiation of localization libraries
106
     * used within current module for multi-languages support
107
     *
108
     * @return NOTHING
109
     */
110
    private function handleLocalizationCommon()
111
    {
112
        $this->handleLanguageIntoSession();
113
        $localizationFile = $this->getCommonLocaleFolder() . '/locale/'
114
                . $this->tCmnSession->get('lang') . '/LC_MESSAGES/'
115
                . $this->commonLibFlags['localization_domain']
116
                . '.mo';
117
        $extrClass        = new \Gettext\Extractors\Mo();
118
        $translations     = $extrClass->fromFile($localizationFile);
119
        $this->tCmnLb     = new \Gettext\Translator();
120
        $this->tCmnLb->loadTranslations($translations);
121
    }
122
123
    protected function initializeSprGlbAndSession()
124
    {
125
        if (is_null($this->tCmnSuperGlobals)) {
126
            $this->tCmnRequest      = new \Symfony\Component\HttpFoundation\Request;
127
            $this->tCmnSuperGlobals = $this->tCmnRequest->createFromGlobals();
128
        }
129
        if (is_null($this->tCmnSession)) {
130
            $sBridge           = new \Symfony\Component\HttpFoundation\Session\Storage\PhpBridgeSessionStorage();
131
            $this->tCmnSession = new \Symfony\Component\HttpFoundation\Session\Session($sBridge);
132
            $this->tCmnSession->start();
133
        }
134
    }
135
136
    /**
137
     * Central function to deal with multi-language messages
138
     *
139
     * @param string $localizedStringCode
140
     * @return string
141
     */
142
    protected function lclMsgCmn($localizedStringCode)
143
    {
144
        if (is_null($this->tCmnLb)) {
145
            $this->settingsCommonLib();
146
            $this->handleLocalizationCommon();
147
        }
148
        return $this->tCmnLb->gettext($localizedStringCode);
149
    }
150
151
    protected function lclMsgCmnNumber($singularString, $pluralString, $numberToEvaluate)
152
    {
153
        if (is_null($this->tCmnLb)) {
154
            $this->settingsCommonLib();
155
            $this->handleLocalizationCommon();
156
        }
157
        return $this->tCmnLb->ngettext($singularString, $pluralString, $numberToEvaluate);
158
    }
159
160
    /**
161
     * Returns proper result from a mathematical division in order to avoid
162
     * Zero division erorr or Infinite results
163
     *
164
     * @param float $fAbove
165
     * @param float $fBelow
166
     * @param mixed $mArguments
167
     * @return decimal
168
     */
169
    protected function setDividedResult($fAbove, $fBelow, $mArguments = 0)
170
    {
171
        if (($fAbove == 0) || ($fBelow == 0)) { // prevent infinite result AND division by 0
172
            return 0;
173
        }
174
        if (is_array($mArguments)) {
175
            $frMinMax = [
176
                'MinFractionDigits' => $mArguments[1],
177
                'MaxFractionDigits' => $mArguments[1],
178
            ];
179
            return $this->setNumberFormat(($fAbove / $fBelow), $frMinMax);
180
        }
181
        return $this->setNumberFormat(round(($fAbove / $fBelow), $mArguments));
182
    }
183
184
    protected function setNumberFormat($content, $features = null)
185
    {
186
        $features = $this->setNumberFormatFeatures($features);
187
        $fmt      = new \NumberFormatter($features['locale'], $features['style']);
188
        $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $features['MinFractionDigits']);
189
        $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $features['MaxFractionDigits']);
190
        return $fmt->format($content);
191
    }
192
193
    private function setNumberFormatFeatures($features)
194
    {
195
        $this->handleLanguageIntoSession();
196
        if (is_null($features)) {
197
            $features = [
198
                'locale'            => $this->tCmnSession->get('lang'),
199
                'style'             => \NumberFormatter::DECIMAL,
200
                'MinFractionDigits' => 0,
201
                'MaxFractionDigits' => 0,
202
            ];
203
        }
204
        if (!array_key_exists('locale', $features)) {
205
            $features['locale'] = $this->tCmnSession->get('lang');
206
        }
207
        if (!array_key_exists('style', $features)) {
208
            $features['style'] = \NumberFormatter::DECIMAL;
209
        }
210
        return $features;
211
    }
212
213
    /**
214
     * Settings
215
     *
216
     * @return NOTHING
217
     */
218
    private function settingsCommonLib()
219
    {
220
        $this->commonLibFlags = [
221
            'available_languages' => [
222
                'en_US' => 'US English',
223
                'ro_RO' => 'Română',
224
                'it_IT' => 'Italiano',
225
            ],
226
            'default_language'    => 'en_US',
227
            'localization_domain' => 'common-locale'
228
        ];
229
    }
230
}
231