From 1044e359464d114a589db3f31e5beaaee7fc0c1f Mon Sep 17 00:00:00 2001 From: Dave Mc Nicoll Date: Tue, 14 Oct 2025 18:18:31 +0000 Subject: [PATCH] - WIP on object initialization for FormContext from request body values --- src/Method/FormContext.php | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/Method/FormContext.php b/src/Method/FormContext.php index 78ecdda..e154513 100644 --- a/src/Method/FormContext.php +++ b/src/Method/FormContext.php @@ -134,15 +134,16 @@ class FormContext implements FormContextInterface $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; } - public function set(string $key, $value) + public function set(string $key, mixed $value) { + if ($this->canWriteProperty($key)) { - $this->$key = $value; + $this->$key = $this->castValue($key, $value); } return $this->formContextValues[$key] = $value; @@ -176,7 +177,7 @@ class FormContext implements FormContextInterface foreach($this->formContextValues as $property => $value) { if ($this->canWriteProperty($property)) { - $this->$property = $value; + $this->$property = $this->castValue($property, $value); $this->formContextDefinedProperties[$property] = true; } } @@ -194,4 +195,22 @@ class FormContext implements FormContextInterface { 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; + } }