From df424ffab5ae356c4e2fcaf146ac98a1c82556e5 Mon Sep 17 00:00:00 2001 From: KJ Date: Tue, 27 Aug 2024 19:01:02 -0400 Subject: [PATCH] Model properties now can be typed as enums. With this PHP 8.0 support is dropped. --- src/Libs/Model.php | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/Libs/Model.php b/src/Libs/Model.php index 7c36bcb..84f4573 100644 --- a/src/Libs/Model.php +++ b/src/Libs/Model.php @@ -242,11 +242,18 @@ class Model { */ protected static function getInstance(array $elem = []): static { - $class = get_called_class(); - $instance = new $class; + $class = get_called_class(); + $instance = new $class; + $reflection = new ReflectionClass($instance); + $properties = $reflection->getProperties(); + $propertyNames = array_column($properties, 'name'); foreach ($elem as $key => $value) { - $instance->$key = $value; + $index = array_search($key, $propertyNames); + if (is_numeric($index) && enum_exists($properties[$index]->getType()->getName())) + $instance->$key = $properties[$index]->getType()->getName()::tryfrom($value); + else + $instance->$key = $value; } return $instance; @@ -278,10 +285,14 @@ class Model { $result[$value] = isset($this->$value) ? $this->$value: null; - foreach ($result as $i => $property) + foreach ($result as $i => $property) { if (gettype($property) == 'boolean') $result[$i] = $property ? '1' : '0'; + if ($property instanceof \UnitEnum) + $result[$i] = $property->value; + } + return $result; }