Completed
Push — master ( d48f6d...0338e7 )
by Daniel
02:45
created

CommonLibLocale::handleLocalizationCommon()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 12
rs 9.4285
cc 1
eloc 10
nc 1
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
    /**
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->tCmnSession->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->tCmnLb)) {
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->tCmnLb)) {
129
            $this->settingsCommonLib();
130
            $this->handleLocalizationCommon();
131
        }
132
        return $this->tCmnLb->ngettext($singularString, $pluralString, $numberToEvaluate);
133
    }
134
135
    /**
136
     * Returns proper result from a mathematical division in order to avoid
137
     * Zero division erorr or Infinite results
138
     *
139
     * @param float $fAbove
140
     * @param float $fBelow
141
     * @param mixed $mArguments
142
     * @return decimal
143
     */
144
    protected function setDividedResult($fAbove, $fBelow, $mArguments = 0)
145
    {
146
        if (($fAbove == 0) || ($fBelow == 0)) { // prevent infinite result AND division by 0
147
            return 0;
148
        }
149
        if (is_array($mArguments)) {
150
            $frMinMax = [
151
                'MinFractionDigits' => $mArguments[1],
152
                'MaxFractionDigits' => $mArguments[1],
153
            ];
154
            return $this->setNumberFormat(($fAbove / $fBelow), $frMinMax);
155
        }
156
        return $this->setNumberFormat(round(($fAbove / $fBelow), $mArguments));
157
    }
158
159
    protected function setNumberFormat($content, $features = null)
160
    {
161
        $features = $this->setNumberFormatFeatures($features);
162
        $fmt      = new \NumberFormatter($features['locale'], $features['style']);
163
        $fmt->setAttribute(\NumberFormatter::MIN_FRACTION_DIGITS, $features['MinFractionDigits']);
164
        $fmt->setAttribute(\NumberFormatter::MAX_FRACTION_DIGITS, $features['MaxFractionDigits']);
165
        return $fmt->format($content);
166
    }
167
168
    private function setNumberFormatFeatures($features)
169
    {
170
        $this->handleLanguageIntoSession();
171
        if (is_null($features)) {
172
            $features = [
173
                'locale'            => $this->tCmnSession->get('lang'),
174
                'style'             => \NumberFormatter::DECIMAL,
175
                'MinFractionDigits' => 0,
176
                'MaxFractionDigits' => 0,
177
            ];
178
        }
179
        if (!array_key_exists('locale', $features)) {
180
            $features['locale'] = $this->tCmnSession->get('lang');
181
        }
182
        if (!array_key_exists('style', $features)) {
183
            $features['style'] = \NumberFormatter::DECIMAL;
184
        }
185
        return $features;
186
    }
187
188
    /**
189
     * Settings
190
     *
191
     * @return NOTHING
192
     */
193
    private function settingsCommonLib()
194
    {
195
        $this->commonLibFlags = [
196
            'available_languages' => [
197
                'en_US' => 'US English',
198
                'ro_RO' => 'Română',
199
                'it_IT' => 'Italiano',
200
            ],
201
            'default_language'    => 'en_US',
202
            'localization_domain' => 'common-locale'
203
        ];
204
    }
205
}
206