Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Money cast support #68

Merged
merged 4 commits into from
Nov 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions src/Casts/MoneyCast.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace Pelmered\FilamentMoneyField\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Money\Currency;
use Money\Money;

class MoneyCast implements CastsAttributes
{
/**
* Cast the given value.
*
* @param array<string, mixed> $attributes
*/
public function get(Model $model, string $key, mixed $value, array $attributes): Money
{
return new Money($value, new Currency('USD'));
}

/**
* Prepare the given value for storage.
*
* @param array<string, mixed> $attributes
*/
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
return $value;
}
}
37 changes: 37 additions & 0 deletions src/Casts/MoneySynth.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace Pelmered\FilamentMoneyField\Casts;

use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
use Money\Currency;
use Money\Money;

class MoneySynth extends Synth
{
public static $key = 'money';

public static function match($target)
{
return $target instanceof Money;
}

public function dehydrate($target)
{
return [[
'amount' => $target->getAmount(),
'currency' => $target->getCurrency(),
], []];
}

public function hydrate($value)
{
if ($value === null) {
return null;
}

return new Money(
$value['amount'],
new Currency($value['currency'])
);
}
}
4 changes: 4 additions & 0 deletions src/FilamentMoneyFieldServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Pelmered\FilamentMoneyField;

use Livewire\Livewire;
use Pelmered\FilamentMoneyField\Casts\MoneySynth;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;

Expand All @@ -20,5 +22,7 @@ public function boot(): void
$this->publishes([
__DIR__.'/../config/filament-money-field.php' => config_path('filament-money-field.php'),
], 'config');

Livewire::propertySynthesizer(MoneySynth::class);
}
}
8 changes: 7 additions & 1 deletion src/Forms/Components/MoneyInput.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Filament\Forms\Components\TextInput;
use Filament\Support\RawJs;
use Money\Money;
use Pelmered\FilamentMoneyField\Concerns\HasMoneyAttributes;
use Pelmered\FilamentMoneyField\Forms\Rules\MaxValueRule;
use Pelmered\FilamentMoneyField\Forms\Rules\MinValueRule;
Expand Down Expand Up @@ -40,7 +41,12 @@ protected function setUp(): void

$this->dehydrateStateUsing(function (MoneyInput $component, $state): ?string {
$currency = $component->getCurrency();
$state = MoneyFormatter::parseDecimal($state, $currency, $component->getLocale(), $this->getDecimals());

if ($state instanceof Money) {
return MoneyFormatter::parseDecimal($state->getAmount(), $state->getCurrency(), $component->getLocale(), $this->getDecimals());
}

$state = MoneyFormatter::parseDecimal($state, $currency, $component->getLocale(), $this->getDecimals());

if (! is_numeric($state)) {
return null;
Expand Down
7 changes: 6 additions & 1 deletion src/MoneyFormatter/MoneyFormatter.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,16 @@ public static function format(
}

public static function formatAsDecimal(
null|int|string $value,
null|int|string|Money $value,
Currency $currency,
string $locale,
int $decimals = 2,
): string {
if ($value instanceof Money) {
$currency = $value->getCurrency();
$value = $value->getAmount();
}

return static::format($value, $currency, $locale, NumberFormatter::DECIMAL, $decimals);
}

Expand Down
3 changes: 3 additions & 0 deletions tests/Components/FormTestComponent.php
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ public function form(Form $form): Form
MoneyInput::make('price')
->minValue(100)
->maxValue(1000),
MoneyInput::make('price_cast')
->minValue(100)
->maxValue(1000),
]);
}

Expand Down
1 change: 1 addition & 0 deletions tests/Database/Factories/PostFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public function definition(): array
'title' => $this->faker->sentence(),
'rating' => $this->faker->numberBetween(1, 10),
'price' => $this->faker->numberBetween(100, 10000),
'price_cast' => $this->faker->numberBetween(100, 10000),
];
}
}
10 changes: 10 additions & 0 deletions tests/FormInputTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -211,3 +211,13 @@
->fill([$field->getName() => 2345345]);
expect($component->getState()['price'])->toEqual('2345345');
});

it('accepts form input money with money cast', function () {
$component = ComponentContainer::make(FormTestComponent::make())
->statePath('data')
->components([MoneyInput::make('price_cast')])
->fill(['price_cast' => 123456]);

dd($component->getState());
expect($component->getState()['price_cast'])->toEqual('123456');
});
2 changes: 2 additions & 0 deletions tests/Models/Post.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
use Pelmered\FilamentMoneyField\Casts\MoneyCast;
use Pelmered\FilamentMoneyField\Tests\Database\Factories\PostFactory;

class Post extends Model
Expand All @@ -16,6 +17,7 @@ class Post extends Model
protected $casts = [
'is_published' => 'boolean',
'tags' => 'array',
'price_cast' => MoneyCast::class,
];

protected $guarded = [];
Expand Down
2 changes: 0 additions & 2 deletions tests/MoneyFormatterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@
namespace Pelmered\FilamentMoneyField\Tests;

use Money\Currency;
use Pelmered\FilamentMoneyField\Tests\TestCase;
use Pelmered\FilamentMoneyField\MoneyFormatter\MoneyFormatter;
use PHPUnit\Framework\Attributes\DataProvider;

uses(TestCase::class);

Expand Down