70 lines
2 KiB
PHP
70 lines
2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Casts;
|
|
|
|
use App\Lib\Discount;
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use RuntimeException;
|
|
|
|
class AsDiscount implements CastsAttributes
|
|
{
|
|
/**
|
|
* Cast the given value.
|
|
*
|
|
* @param Model $model
|
|
* @param mixed $value
|
|
*
|
|
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
|
|
*
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
|
|
*
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
|
|
*/
|
|
public function get($model, string $key, $value, array $attributes): Discount
|
|
{
|
|
// phpcs:enable
|
|
$inputData = \json_decode($value, true);
|
|
|
|
return Discount::make(...\array_values($inputData));
|
|
}
|
|
|
|
/**
|
|
* Prepare the given value for storage.
|
|
*
|
|
* @param Model $model
|
|
* @param mixed $value
|
|
* @return string Json encoded \App\Lib\Inputs\Definition\Input
|
|
*
|
|
* @phpcs:disable Squiz.Commenting.FunctionComment.TypeHintMissing
|
|
*
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
|
|
*
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
|
|
*/
|
|
public function set($model, string $key, $value, array $attributes)
|
|
{
|
|
// phpcs:enable
|
|
$this->assertIsInput($value);
|
|
|
|
/** @var Discount $value */
|
|
return $value->toJson();
|
|
}
|
|
|
|
/**
|
|
* Assert is instance of \App\Lib\Discount
|
|
*
|
|
* @throws RuntimeException If the value is not an input.
|
|
*/
|
|
private function assertIsInput(mixed $value): void
|
|
{
|
|
if (! \is_object($value) || ! ($value instanceof Discount)) {
|
|
$value = \json_encode($value);
|
|
throw new RuntimeException(
|
|
self::class . ' needs value to be array of \'' . Discount::class . "' given is {$value}"
|
|
);
|
|
}
|
|
}
|
|
}
|