45 lines
1.2 KiB
PHP
45 lines
1.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Casts;
|
|
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Money\Currency;
|
|
use Money\Money;
|
|
|
|
/** @implements CastsAttributes<Money,Money> */
|
|
class MoneyCast implements CastsAttributes
|
|
{
|
|
/** @param array<string, mixed> $attributes */
|
|
public function get(Model $model, string $key, mixed $value, array $attributes): Money
|
|
{
|
|
$currency = $this->getCurrency();
|
|
|
|
if (! is_numeric($value)) {
|
|
throw new \InvalidArgumentException('The given value is not numeric.');
|
|
}
|
|
|
|
if (! is_string($value) && ! is_int($value)) {
|
|
throw new \InvalidArgumentException('The given value must be a string or integer.');
|
|
}
|
|
|
|
return new Money($value, $currency);
|
|
}
|
|
|
|
/** @param array<string, mixed> $attributes */
|
|
public function set(Model $model, string $key, mixed $value, array $attributes): string
|
|
{
|
|
if ($value instanceof Money) {
|
|
return $value->getAmount();
|
|
}
|
|
|
|
throw new \InvalidArgumentException('The given value is not an instance of Money.');
|
|
}
|
|
|
|
protected function getCurrency(): Currency
|
|
{
|
|
return resolve(Currency::class);
|
|
}
|
|
}
|