- Added some more flexibility to castValue method

This commit is contained in:
Dave M. 2026-07-14 15:19:25 +00:00
parent e093495909
commit 00e5a0380a
2 changed files with 19 additions and 0 deletions

View File

@ -0,0 +1,8 @@
<?php
namespace Picea\Ui\Method\Context;
interface FormContextCastableInterface
{
public static function instance(mixed $value);
}

View File

@ -215,6 +215,14 @@ class FormContext implements FormContextInterface
protected function castValue(string $property, mixed $value) : mixed
{
$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,
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),
@ -233,6 +241,9 @@ class FormContext implements FormContextInterface
return $cast($type->getName());
}
}
elseif ($types->isBuiltin()) {
return $cast($types->getName());
}
return $value;
}