feat(model): add type casting for DateTime
This commit is contained in:
@@ -321,7 +321,7 @@ class Model
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles type casting for properties, especially for Enums.
|
* Handles type casting for properties
|
||||||
*
|
*
|
||||||
* @param ReflectionProperty $property
|
* @param ReflectionProperty $property
|
||||||
* @param mixed $value
|
* @param mixed $value
|
||||||
@@ -331,17 +331,26 @@ class Model
|
|||||||
protected static function castValue(ReflectionProperty $property, mixed $value): mixed
|
protected static function castValue(ReflectionProperty $property, mixed $value): mixed
|
||||||
{
|
{
|
||||||
$type = $property->getType();
|
$type = $property->getType();
|
||||||
if (!$type || !enum_exists($typeName = $type->getName())) {
|
if (!$type) {
|
||||||
return $value;
|
return $value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
$typeName = $type->getName();
|
||||||
|
|
||||||
|
// Enum cast
|
||||||
|
if (enum_exists($typeName)) {
|
||||||
if (method_exists($typeName, 'tryFrom')) {
|
if (method_exists($typeName, 'tryFrom')) {
|
||||||
return $typeName::tryFrom($value);
|
return $typeName::tryFrom($value);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (in_array($value, array_column($typeName::cases(), 'name'))) {
|
if (in_array($value, array_column($typeName::cases(), 'name'))) {
|
||||||
return $typeName::{$value};
|
return $typeName::{$value};
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// DateTime cast
|
||||||
|
if (is_subclass_of($typeName, \DateTimeInterface::class)) {
|
||||||
|
return $value ? new $typeName($value) : null;
|
||||||
|
}
|
||||||
|
|
||||||
return $value;
|
return $value;
|
||||||
}
|
}
|
||||||
@@ -391,6 +400,10 @@ class Model
|
|||||||
return $value->value ?? $value->name;
|
return $value->value ?? $value->name;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if ($value instanceof \DateTimeInterface) {
|
||||||
|
return $value->format('Y-m-d H:i:s');
|
||||||
|
}
|
||||||
|
|
||||||
return $value;
|
return $value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user