adding money castable

This commit is contained in:
2022-12-07 11:41:43 -07:00
parent 3f340d57fc
commit 0c8a6c410d

View File

@ -0,0 +1,51 @@
<?php
namespace App\Models\Casts;
use Brick\Money\Money;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class MoneyCastable implements CastsAttributes
{
/**
* Get the value from the database and modify it to casted type
* before returning.
*
* @package App\Models\Casts\MoneyCastable
* @since 1.0.0
*
* @param \Illuminate\Database\Eloquent\Model $model The Model that is being used
* @param string $key The attribute key
* @param mixed $value The value stored in the database
* @param array $attributes The array of model attributes
*
* @return \Brick\Money\Money
*/
public function get(Model $model, string $key, $value, array $attributes): Money
{
return Money::ofMinor($attributes['amount'], $attributes['currency']);
}
/**
* Store the data .
*
* @package App\Models\Casts\MoneyCastable
* @since 1.0.0
*
* @param \Illuminate\Database\Eloquent\Model $model The Model that is being used
* @param string $key The attribute key
* @param mixed $value The value stored in the database
* @param array $attributes The array of model attributes
*
* @return mixed
*/
public function set(Model $model, string $key, $value, array $attributes)
{
if (! $value instanceof Money) {
return $value;
}
return $value->getMinorAmount()->toInt();
}
}