From cb008596f1085a29ac83c6f5f8d0bdfad9db389a Mon Sep 17 00:00:00 2001 From: "Leandro C. Ferreira" Date: Wed, 27 Mar 2024 17:38:11 -0300 Subject: [PATCH] wip --- src/Money.php | 62 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 43 insertions(+), 19 deletions(-) diff --git a/src/Money.php b/src/Money.php index 4218e3e..19ca5be 100644 --- a/src/Money.php +++ b/src/Money.php @@ -5,6 +5,7 @@ use Closure; use Filament\Forms\Components\TextInput; use Illuminate\Support\Str; +use Illuminate\Support\Stringable; class Money extends TextInput { @@ -27,13 +28,10 @@ protected function setUp(): void }', 'x-on:keyup' => 'function() { - var money = $el.value.replace(/\D/g, ""); - money = (money / 100).toFixed(2) + ""; - money = money.replace(".", ","); - money = money.replace(/(\d)(\d{3})(\d{3}),/g, "$1.$2.$3,"); - money = money.replace(/(\d)(\d{3}),/g, "$1.$2,"); - - $el.value = money; + var money = $el.value; + money = money.replace(/\D/g, \'\'); + money = (parseFloat(money) / 100).toLocaleString(\'pt-BR\', { minimumFractionDigits: 2 }); + $el.value = money === \'NaN\' ? \'0,00\' : money; }', ]) ->dehydrateMask() @@ -43,20 +41,10 @@ protected function setUp(): void public function dehydrateMask(bool|Closure $condition = true): static { - if ($condition) { - $this->dehydrateStateUsing( - fn ($state): ?float => $state ? - floatval( - Str::of($state) - ->replace('.', '') - ->replace(',', '.') - ->toString() - ) * 10 : - null - ); + $this->dehydrateStateUsing(fn (?string $state): ?float => $this->convertToFloat($state)); } else { - $this->dehydrateStateUsing(null); + $this->dehydrateStateUsing(fn (?string $state): ?string => $this->convertToNumberFormat($state)); } return $this; @@ -68,4 +56,40 @@ public function initialValue(null|string|int|float|Closure $value = '0,00'): sta return $this; } + + private function sanitizeState(?string $state): ?Stringable + { + $state = Str::of($state) + ->replace('.', '') + ->replace(',', ''); + + return $state ?? null; + } + + private function convertToFloat(Stringable|string|null $state): float + { + $state = $this->sanitizeState($state); + + if (! $state) { + return 0; + } + + if ($state->length() > 2) { + $state = $state + ->substr(0, $state->length() - 2) + ->append('.') + ->append($state->substr($state->length() - 2, 2)); + } else { + $state = $state->prepend('0.'); + } + + return floatval($state->toString()) ?? 0; + } + + private function convertToNumberFormat(string $state): string + { + $state = $this->convertToFloat($state); + + return number_format($state, 2, ',', '.') ?? 0; + } }