5
5
use Closure ;
6
6
use Filament \Forms \Components \TextInput ;
7
7
use Illuminate \Support \Str ;
8
+ use Illuminate \Support \Stringable ;
8
9
9
10
class Money extends TextInput
10
11
{
@@ -27,13 +28,10 @@ protected function setUp(): void
27
28
} ' ,
28
29
29
30
'x-on:keyup ' => 'function() {
30
- var money = $el.value.replace(/\D/g, "");
31
- money = (money / 100).toFixed(2) + "";
32
- money = money.replace(".", ",");
33
- money = money.replace(/(\d)(\d{3})(\d{3}),/g, "$1.$2.$3,");
34
- money = money.replace(/(\d)(\d{3}),/g, "$1.$2,");
35
-
36
- $el.value = money;
31
+ var money = $el.value;
32
+ money = money.replace(/\D/g, \'\');
33
+ money = (parseFloat(money) / 100).toLocaleString( \'pt-BR \', { minimumFractionDigits: 2 });
34
+ $el.value = money === \'NaN \' ? \'0,00 \' : money;
37
35
} ' ,
38
36
])
39
37
->dehydrateMask ()
@@ -43,20 +41,10 @@ protected function setUp(): void
43
41
44
42
public function dehydrateMask (bool |Closure $ condition = true ): static
45
43
{
46
-
47
44
if ($ condition ) {
48
- $ this ->dehydrateStateUsing (
49
- fn ($ state ): ?float => $ state ?
50
- floatval (
51
- Str::of ($ state )
52
- ->replace ('. ' , '' )
53
- ->replace (', ' , '. ' )
54
- ->toString ()
55
- ) * 10 :
56
- null
57
- );
45
+ $ this ->dehydrateStateUsing (fn (?string $ state ): ?float => $ this ->convertToFloat ($ state ));
58
46
} else {
59
- $ this ->dehydrateStateUsing (null );
47
+ $ this ->dehydrateStateUsing (fn (? string $ state ): ? string => $ this -> convertToNumberFormat ( $ state ) );
60
48
}
61
49
62
50
return $ this ;
@@ -68,4 +56,40 @@ public function initialValue(null|string|int|float|Closure $value = '0,00'): sta
68
56
69
57
return $ this ;
70
58
}
59
+
60
+ private function sanitizeState (?string $ state ): ?Stringable
61
+ {
62
+ $ state = Str::of ($ state )
63
+ ->replace ('. ' , '' )
64
+ ->replace (', ' , '' );
65
+
66
+ return $ state ?? null ;
67
+ }
68
+
69
+ private function convertToFloat (Stringable |string |null $ state ): float
70
+ {
71
+ $ state = $ this ->sanitizeState ($ state );
72
+
73
+ if (! $ state ) {
74
+ return 0 ;
75
+ }
76
+
77
+ if ($ state ->length () > 2 ) {
78
+ $ state = $ state
79
+ ->substr (0 , $ state ->length () - 2 )
80
+ ->append ('. ' )
81
+ ->append ($ state ->substr ($ state ->length () - 2 , 2 ));
82
+ } else {
83
+ $ state = $ state ->prepend ('0. ' );
84
+ }
85
+
86
+ return floatval ($ state ->toString ()) ?? 0 ;
87
+ }
88
+
89
+ private function convertToNumberFormat (string $ state ): string
90
+ {
91
+ $ state = $ this ->convertToFloat ($ state );
92
+
93
+ return number_format ($ state , 2 , ', ' , '. ' ) ?? 0 ;
94
+ }
71
95
}
0 commit comments