-
Notifications
You must be signed in to change notification settings - Fork 0
/
Helper.php
64 lines (57 loc) · 2.16 KB
/
Helper.php
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
<?php
if(!function_exists('forHumansPtBr')){
/**
* Convert the given Number::forHumans to ordinal pt_BR locale.
*
* @param string $formattedNumber from Number::forHumans, already formatted in English ie.: '10 thousand','1 million'
* @param ?bool $abreviation returns an abreviation of the number, ie.: '10 mil','1 mi','1 bi'
* @return string
*/
function forHumansPtBr(string $formattedNumber, ?bool $abreviation = false) : string
{
$translationsSingular = [
'thousand' => 'mil',
'million' => 'milhão',
'billion' => 'bilhão',
'trillion' => 'trilhão',
'quadrillion' => 'quadrilhão',
];
$translationsPlural = [
'thousand' => 'mil',
'million' => 'milhões',
'billion' => 'bilhões',
'trillion' => 'trilhões',
'quadrillion' => 'quadrilhões',
];
// Abreviation format
$translationsAbreviation = [
'thousand' => 'mil',
'million' => 'mi',
'billion' => 'bi',
'trillion' => 'tri',
'quadrillion' => 'quadri',
];
// and another option could be:
// $translationsAbreviation = [
// 'thousand' => 'K',
// 'million' => 'M',
// 'billion' => 'B',
// 'trillion' => 'T',
// 'quadrillion' => 'Q',
// ];
preg_match('/([\d.]+)\s*([a-z]+)/i', $formattedNumber, $matches);
if (isset($matches[1]) && isset($matches[2])) {
$number = $matches[1];
$unit = $matches[2];
if ($abreviation) {
$translations = $translationsAbreviation;
} else {
$translations = $number == 1 ? $translationsSingular : $translationsPlural;
}
$translatedUnit = $translations[$unit] ?? $unit;
return "$number $translatedUnit";
}
// Return the original input if no translation is possible
return $formattedNumber;
}
}