1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
|
<?php
/**
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*
*/
namespace Piwik;
use Piwik\Container\StaticContainer;
use Piwik\Translation\Translator;
/**
* Class NumberFormatter
*
* Used to format numbers according to current language
*/
class NumberFormatter
{
/** @var Translator */
protected $translator;
/** @var array cached patterns per language */
protected $patterns;
/** @var array cached symbols per language */
protected $symbols;
/**
* Loads all required data from Intl plugin
*
* TODO: instead of going directly through Translator, there should be a specific class
* that gets needed characters (ie, NumberFormatSource). The default implementation
* can use the Translator. This will make it easier to unit test NumberFormatter,
* w/o needing the Piwik Environment.
*
* @return NumberFormatter
*/
public function __construct(Translator $translator)
{
$this->translator = $translator;
}
/**
* Formats a given number or percent value (if $value starts or ends with a %)
*
* @param string|int|float $value
* @param int $maximumFractionDigits
* @param int $minimumFractionDigits
* @return mixed|string
*/
public function format($value, $maximumFractionDigits=0, $minimumFractionDigits=0)
{
if (is_string($value)
&& trim($value, '%') != $value
) {
return $this->formatPercent($value, $maximumFractionDigits, $minimumFractionDigits);
}
return $this->formatNumber($value, $maximumFractionDigits, $minimumFractionDigits);
}
/**
* Formats a given number
*
* @see \Piwik\NumberFormatter::format()
*
* @param string|int|float $value
* @param int $maximumFractionDigits
* @param int $minimumFractionDigits
* @return mixed|string
*/
public function formatNumber($value, $maximumFractionDigits=0, $minimumFractionDigits=0)
{
$pattern = $this->getPattern($value, 'Intl_NumberFormatNumber');
return $this->formatNumberWithPattern($pattern, $value, $maximumFractionDigits, $minimumFractionDigits);
}
/**
* Formats given number as percent value
* @param string|int|float $value
* @param int $maximumFractionDigits
* @param int $minimumFractionDigits
* @return mixed|string
*/
public function formatPercent($value, $maximumFractionDigits=0, $minimumFractionDigits=0)
{
$newValue = trim($value, " \0\x0B%");
if (!is_numeric($newValue)) {
return $value;
}
$pattern = $this->getPattern($value, 'Intl_NumberFormatPercent');
return $this->formatNumberWithPattern($pattern, $newValue, $maximumFractionDigits, $minimumFractionDigits);
}
/**
* Formats given number as percent value, but keep the leading + sign if found
*
* @param $value
* @return string
*/
public function formatPercentEvolution($value)
{
$isPositiveEvolution = !empty($value) && ($value > 0 || $value[0] == '+');
$formatted = self::formatPercent($value);
if ($isPositiveEvolution) {
// $this->symbols has already been initialized from formatPercent().
$language = $this->translator->getCurrentLanguage();
return $this->symbols[$language]['+'] . $formatted;
}
return $formatted;
}
/**
* Formats given number as percent value
* @param string|int|float $value
* @param string $currency
* @param int $precision
* @return mixed|string
*/
public function formatCurrency($value, $currency, $precision=2)
{
$newValue = trim($value, " \0\x0B$currency");
if (!is_numeric($newValue)) {
return $value;
}
$pattern = $this->getPattern($value, 'Intl_NumberFormatCurrency');
if ($newValue == round($newValue)) {
// if no fraction digits available, don't show any
$value = $this->formatNumberWithPattern($pattern, $newValue, 0, 0);
} else {
// show given count of fraction digits otherwise
$value = $this->formatNumberWithPattern($pattern, $newValue, $precision, $precision);
}
return str_replace('¤', $currency, $value);
}
/**
* Returns the relevant pattern for the given number.
*
* @param string $value
* @param string $translationId
* @return string
*/
protected function getPattern($value, $translationId)
{
$language = $this->translator->getCurrentLanguage();
if (!isset($this->patterns[$language][$translationId])) {
$this->patterns[$language][$translationId] = $this->parsePattern($this->translator->translate($translationId));
}
list($positivePattern, $negativePattern) = $this->patterns[$language][$translationId];
$negative = $this->isNegative($value);
return $negative ? $negativePattern : $positivePattern;
}
/**
* Parses the given pattern and returns patterns for positive and negative numbers
*
* @param string $pattern
* @return array
*/
protected function parsePattern($pattern)
{
$patterns = explode(';', $pattern);
if (!isset($patterns[1])) {
// No explicit negative pattern was provided, construct it.
$patterns[1] = '-' . $patterns[0];
}
return $patterns;
}
/**
* Formats the given number with the given pattern
*
* @param string $pattern
* @param string|int|float $value
* @param int $maximumFractionDigits
* @param int $minimumFractionDigits
* @return mixed|string
*/
protected function formatNumberWithPattern($pattern, $value, $maximumFractionDigits=0, $minimumFractionDigits=0)
{
if (!is_numeric($value)) {
return $value;
}
$usesGrouping = (strpos($pattern, ',') !== false);
// if pattern has number groups, parse them.
if ($usesGrouping) {
preg_match('/#+0/', $pattern, $primaryGroupMatches);
$primaryGroupSize = $secondaryGroupSize = strlen($primaryGroupMatches[0]);
$numberGroups = explode(',', $pattern);
// check for distinct secondary group size.
if (count($numberGroups) > 2) {
$secondaryGroupSize = strlen($numberGroups[1]);
}
}
// Ensure that the value is positive and has the right number of digits.
$negative = $this->isNegative($value);
$signMultiplier = $negative ? '-1' : '1';
$value = $value / $signMultiplier;
$value = round($value, $maximumFractionDigits);
// Split the number into major and minor digits.
$valueParts = explode('.', $value);
$majorDigits = $valueParts[0];
// Account for maximumFractionDigits = 0, where the number won't
// have a decimal point, and $valueParts[1] won't be set.
$minorDigits = isset($valueParts[1]) ? $valueParts[1] : '';
if ($usesGrouping) {
// Reverse the major digits, since they are grouped from the right.
$majorDigits = array_reverse(str_split($majorDigits));
// Group the major digits.
$groups = array();
$groups[] = array_splice($majorDigits, 0, $primaryGroupSize);
while (!empty($majorDigits)) {
$groups[] = array_splice($majorDigits, 0, $secondaryGroupSize);
}
// Reverse the groups and the digits inside of them.
$groups = array_reverse($groups);
foreach ($groups as &$group) {
$group = implode(array_reverse($group));
}
// Reconstruct the major digits.
$majorDigits = implode(',', $groups);
}
if ($minimumFractionDigits < $maximumFractionDigits) {
// Strip any trailing zeroes.
$minorDigits = rtrim($minorDigits, '0');
if (strlen($minorDigits) < $minimumFractionDigits) {
// Now there are too few digits, re-add trailing zeroes
// until the desired length is reached.
$neededZeroes = $minimumFractionDigits - strlen($minorDigits);
$minorDigits .= str_repeat('0', $neededZeroes);
}
}
// Assemble the final number and insert it into the pattern.
$value = $minorDigits ? $majorDigits . '.' . $minorDigits : $majorDigits;
$value = preg_replace('/#(?:[\.,]#+)*0(?:[,\.][0#]+)*/', $value, $pattern);
// Localize the number.
$value = $this->replaceSymbols($value);
return $value;
}
/**
* Replaces number symbols with their localized equivalents.
*
* @param string $value The value being formatted.
*
* @return string
*
* @see http://cldr.unicode.org/translation/number-symbols
*/
protected function replaceSymbols($value)
{
$language = $this->translator->getCurrentLanguage();
if (!isset($this->symbols[$language])) {
$this->symbols[$language] = array(
'.' => $this->translator->translate('Intl_NumberSymbolDecimal'),
',' => $this->translator->translate('Intl_NumberSymbolGroup'),
'+' => $this->translator->translate('Intl_NumberSymbolPlus'),
'-' => $this->translator->translate('Intl_NumberSymbolMinus'),
'%' => $this->translator->translate('Intl_NumberSymbolPercent'),
);
}
return strtr($value, $this->symbols[$language]);
}
/**
* @param $value
* @return bool
*/
protected function isNegative($value)
{
return $value < 0;
}
/**
* @deprecated
* @return self
*/
public static function getInstance()
{
return StaticContainer::get('Piwik\NumberFormatter');
}
}
|