File: NumberFormatter.php

package info (click to toggle)
matomo 5.8.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 95,068 kB
  • sloc: php: 289,425; xml: 127,249; javascript: 112,130; python: 202; sh: 178; makefile: 20; sql: 10
file content (419 lines) | stat: -rw-r--r-- 14,092 bytes parent folder | download
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
<?php

/**
 * Matomo - free/libre analytics platform
 *
 * @link    https://matomo.org
 * @license https://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;
    }

    /**
     * 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 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 a given number in compact format
     *
     * @see \Piwik\NumberFormatter::format()
     *
     * @param string|int|float $value
     * @return mixed|string
     */
    public function formatNumberCompact($value)
    {
        [$compactPattern, $factor] = $this->determineCorrectCompactPattern('Intl_NumberFormatNumberCompact', $value);

        // In case no special formatting should be used, we use the default number format
        if (round($value) < 1000 || $compactPattern === '0') {
            $maximumFractionDigits = $this->getMaxFractionDigitsForCompactFormat(round($value));

            return $this->formatNumber($value, $maximumFractionDigits, 0);
        }

        return $this->formatCompact($compactPattern, $factor, $value);
    }

    /**
     * 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 || substr($value, 0, 1) === '+');

        $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 currency value
     *
     * @param string|int|float $value
     * @param string $currency
     * @param int $precision
     * @return mixed|string
     */
    public function formatCurrency($value, $currency, $precision = 2)
    {
        $newValue = trim(strval($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);
    }


    /**
     * Formats a given number as currency value in compact format
     *
     * @see \Piwik\NumberFormatter::format()
     *
     * @param string|int|float $value
     * @return mixed|string
     */
    public function formatCurrencyCompact($value, $currency)
    {
        [$compactPattern, $factor] = $this->determineCorrectCompactPattern('Intl_NumberFormatCurrencyCompact', $value);

        // In case no special formatting should be used, we use the default number format
        if (round($value) < 1000 || $compactPattern === '0') {
            $maximumFractionDigits = $this->getMaxFractionDigitsForCompactFormat(round($value));

            return $this->formatCurrency($value, $currency, 0);
        }

        return str_replace('¤', $currency, $this->formatCompact($compactPattern, $factor, $value));
    }

    private function getMaxFractionDigitsForCompactFormat(int $valueLength): int
    {
        return $valueLength === 1 ? 1 : 0;
    }

    private function determineCorrectCompactPattern(string $patternPrefix, $value)
    {
        $finalFactor = 0;
        $patternId = '';

        if (round($value) < 1000) {
            return ['0', 1];
        }

        for ($factor = 1000; $factor <= 10000000000000000000; $factor *= 10) {
            $patternOne = $patternPrefix . $factor . 'One';
            $patternOther = $patternPrefix . $factor . 'Other';

            if (
                round($value / $factor) === 1.0
                && $this->translator->translate($patternOne) !== ''
            ) {
                $finalFactor = $factor;
                $patternId = $patternOne;
            } elseif (
                round($value / $factor) >= 1
                && $this->translator->translate($patternOther) !== ''
            ) {
                $finalFactor = $factor;
                $patternId = $patternOther;
            }

            if ($this->translator->translate($patternId) !== $patternId) {
                $charCount = substr_count($this->translator->translate($patternId), '0');

                if (round(($value * pow(10, $charCount)) / ($factor * 10)) < pow(10, $charCount)) {
                    break;
                }
            }
        }

        return [$this->translator->translate($patternId), $finalFactor];
    }

    private function formatCompact(string $pattern, int $factor, $value)
    {
        $charCount = substr_count($pattern, '0');

        if ($charCount > 1) {
            $factor /= pow(10, ($charCount - 1));
        }

        $maximumFractionDigits = $this->getMaxFractionDigitsForCompactFormat($charCount);

        // cut off numbers after a certain decimal, as formatNumber would round otherwise
        $digitCountFactor = pow(10, $maximumFractionDigits);
        $value = round(($value / $factor) * $digitCountFactor) / $digitCountFactor;

        $formattedNumber = $this->formatNumber($value, $maximumFractionDigits, 0);

        return preg_replace(['/(0+)/', '/(\'\.\')/'], [$formattedNumber, '.'], $pattern);
    }

    /**
     * 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;
    }

    /**
     * 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 = strlen($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 https://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(NumberFormatter::class);
    }

    public function clearCache()
    {
        $this->patterns = [];
        $this->symbols = [];
    }
}