- Added some more flexibility to castValue method
This commit is contained in:
parent
e093495909
commit
00e5a0380a
8
src/Method/Context/FormContextCastableInterface.php
Normal file
8
src/Method/Context/FormContextCastableInterface.php
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Picea\Ui\Method\Context;
|
||||||
|
|
||||||
|
interface FormContextCastableInterface
|
||||||
|
{
|
||||||
|
public static function instance(mixed $value);
|
||||||
|
}
|
||||||
@ -215,6 +215,14 @@ class FormContext implements FormContextInterface
|
|||||||
protected function castValue(string $property, mixed $value) : mixed
|
protected function castValue(string $property, mixed $value) : mixed
|
||||||
{
|
{
|
||||||
$cast = fn($e) => match(true) {
|
$cast = fn($e) => match(true) {
|
||||||
|
is_a($e, Context\FormContextCastableInterface::class, true) => $e::instance($value),
|
||||||
|
$e === "array" => (function(array|string $value) use ($property) {
|
||||||
|
if (is_string($value)) {
|
||||||
|
return json_validate($value) ? json_decode($value, true) ?? [] : throw new \InvalidArgumentException("Field '$property' is awaiting JSON encoded content.");
|
||||||
|
}
|
||||||
|
|
||||||
|
return $value;
|
||||||
|
})($value),
|
||||||
is_null($value) => null,
|
is_null($value) => null,
|
||||||
enum_exists($e) => ( $value instanceof \BackedEnum ? $value : $e::tryFrom($value) ) ?? throw new \InvalidArgumentException(sprintf("Field '\$$property' awaiting values : '%s'.", implode("', '", array_map(fn($e) => $e->value, $e::cases())))),
|
enum_exists($e) => ( $value instanceof \BackedEnum ? $value : $e::tryFrom($value) ) ?? throw new \InvalidArgumentException(sprintf("Field '\$$property' awaiting values : '%s'.", implode("', '", array_map(fn($e) => $e->value, $e::cases())))),
|
||||||
function_exists($e) => $e($value),
|
function_exists($e) => $e($value),
|
||||||
@ -233,6 +241,9 @@ class FormContext implements FormContextInterface
|
|||||||
return $cast($type->getName());
|
return $cast($type->getName());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
elseif ($types->isBuiltin()) {
|
||||||
|
return $cast($types->getName());
|
||||||
|
}
|
||||||
|
|
||||||
return $value;
|
return $value;
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user