- WIP on object initialization for FormContext from request body values

This commit is contained in:
Dave Mc Nicoll 2025-10-14 18:18:31 +00:00
parent 6ccf07825a
commit 1044e35946

View File

@ -134,15 +134,16 @@ class FormContext implements FormContextInterface
$this->delete($key); $this->delete($key);
} }
public function get(string $key, $default = null) public function get(string $key, mixed $default = null)
{ {
return $this->has($key) ? $this->formContextValues[$key] : $default; return $this->has($key) ? $this->formContextValues[$key] : $default;
} }
public function set(string $key, $value) public function set(string $key, mixed $value)
{ {
if ($this->canWriteProperty($key)) { if ($this->canWriteProperty($key)) {
$this->$key = $value; $this->$key = $this->castValue($key, $value);
} }
return $this->formContextValues[$key] = $value; return $this->formContextValues[$key] = $value;
@ -176,7 +177,7 @@ class FormContext implements FormContextInterface
foreach($this->formContextValues as $property => $value) { foreach($this->formContextValues as $property => $value) {
if ($this->canWriteProperty($property)) { if ($this->canWriteProperty($property)) {
$this->$property = $value; $this->$property = $this->castValue($property, $value);
$this->formContextDefinedProperties[$property] = true; $this->formContextDefinedProperties[$property] = true;
} }
} }
@ -194,4 +195,22 @@ class FormContext implements FormContextInterface
{ {
return $this->formContextDefinedProperties[$property] ?? false; return $this->formContextDefinedProperties[$property] ?? false;
} }
protected function castValue(string $property, mixed $value) : mixed
{
$isEnum = fn($e) => enum_exists($e) ? $e::tryFrom($value) : $value;
$types = ( new \ReflectionProperty($this, $property) )->getType();
if ($types instanceof \ReflectionNamedType) {
$value = $isEnum($types->getName());
}
elseif ($types instanceof \ReflectionIntersectionType || $types instanceof \ReflectionUnionType) {
foreach($types->getTypes() as $type) {
$value = $isEnum($type->getName());
}
}
return $value;
}
} }