68 lines
2.6 KiB
PHP
68 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Casts;
|
|
|
|
use App\Enums\Formularies\InputTypeEnum;
|
|
use App\Lib\Inputs\Definition\Input;
|
|
use App\Lib\Inputs\Definition\InputData;
|
|
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
|
|
class AsInput implements CastsAttributes
|
|
{
|
|
/**
|
|
* Cast the given value.
|
|
*
|
|
* @param \Illuminate\Database\Eloquent\Model $model
|
|
* @param string $key
|
|
* @param mixed $value
|
|
* @param array $attributes
|
|
* @return \App\Lib\Inputs\Definition\Input
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
|
|
*/
|
|
public function get(Model $model, string $key, mixed $value, array $attributes): Input
|
|
{
|
|
// phpcs:enable
|
|
/** @var array<string, integer|string|boolean> $inputData */
|
|
$inputData = \json_decode($value, true);
|
|
$inputClass = InputTypeEnum::make($inputData['type'])->getInputClass();
|
|
return $inputClass::from(InputData::make(...\array_values($inputData)), $inputData['required'] ?? false);
|
|
}
|
|
|
|
/**
|
|
* Prepare the given value for storage.
|
|
*
|
|
* @param \Illuminate\Database\Eloquent\Model $model
|
|
* @param string $key
|
|
* @param mixed $value
|
|
* @param array $attributes
|
|
* @return string Json encoded \App\Lib\Inputs\Definition\Input
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceBeforeLastUsed
|
|
* @phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter.FoundInImplementedInterfaceAfterLastUsed
|
|
*/
|
|
public function set(Model $model, string $key, mixed $value, array $attributes): string
|
|
{
|
|
// phpcs:enable
|
|
$this->assertIsInput($value);
|
|
/** @var \App\Lib\Inputs\Definition\Input $value */
|
|
return $value->toJson();
|
|
}
|
|
|
|
/**
|
|
* Assert is instance of \App\Lib\Inputs\Definition\Input
|
|
*
|
|
* @param mixed $value
|
|
* @return void
|
|
* @throws \RuntimeException If the value is not an input.
|
|
*/
|
|
private function assertIsInput(mixed $value): void
|
|
{
|
|
if (!\is_object($value) or !\in_array(Input::class, \class_parents($value))) {
|
|
$value = \json_encode($value);
|
|
throw new \RuntimeException(
|
|
__CLASS__ . ' needs value to be array of \'' . Input::class . "' given is {$value}"
|
|
);
|
|
}
|
|
}
|
|
}
|