From b95747bfe0309340a2642b33c2d134c2ecba1d5b Mon Sep 17 00:00:00 2001 From: kj Date: Fri, 19 Jun 2026 15:14:25 -0300 Subject: [PATCH] feat(model): add type casting for DateTime --- src/Libs/Model.php | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/src/Libs/Model.php b/src/Libs/Model.php index d9cfc96..2cf4c88 100644 --- a/src/Libs/Model.php +++ b/src/Libs/Model.php @@ -321,7 +321,7 @@ class Model } /** - * Handles type casting for properties, especially for Enums. + * Handles type casting for properties * * @param ReflectionProperty $property * @param mixed $value @@ -331,16 +331,25 @@ class Model protected static function castValue(ReflectionProperty $property, mixed $value): mixed { $type = $property->getType(); - if (!$type || !enum_exists($typeName = $type->getName())) { + if (!$type) { return $value; } - if (method_exists($typeName, 'tryFrom')) { - return $typeName::tryFrom($value); + $typeName = $type->getName(); + + // Enum cast + if (enum_exists($typeName)) { + if (method_exists($typeName, 'tryFrom')) { + return $typeName::tryFrom($value); + } + if (in_array($value, array_column($typeName::cases(), 'name'))) { + return $typeName::{$value}; + } } - if (in_array($value, array_column($typeName::cases(), 'name'))) { - return $typeName::{$value}; + // DateTime cast + if (is_subclass_of($typeName, \DateTimeInterface::class)) { + return $value ? new $typeName($value) : null; } return $value; @@ -391,6 +400,10 @@ class Model return $value->value ?? $value->name; } + if ($value instanceof \DateTimeInterface) { + return $value->format('Y-m-d H:i:s'); + } + return $value; }