adding money castable
This commit is contained in:
51
src/app/Models/Casts/MoneyCastable.php
Normal file
51
src/app/Models/Casts/MoneyCastable.php
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
Reference in New Issue
Block a user