diff --git a/src/Libs/Model.php b/src/Libs/Model.php index bc3e390..a3e617a 100644 --- a/src/Libs/Model.php +++ b/src/Libs/Model.php @@ -139,9 +139,9 @@ class Model throw new Exception( "\nError at query to database.\n" . - "Query: $query\n" . - "Vars: $vars\n" . - "Error:\n" . $e->getMessage() + "Query: $query\n" . + "Vars: $vars\n" . + "Error:\n" . $e->getMessage() ); } @@ -256,14 +256,20 @@ class Model $instance = new $class(); $reflection = new ReflectionClass($instance); $properties = $reflection->getProperties(); - $propertyNames = array_column($properties, 'name'); + $propertyNames = array_map(function ($property) { + return static::camelCaseToSnakeCase($property->name); + }, $properties); foreach ($elem as $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); + if (is_numeric($index)) { + if (enum_exists($properties[$index]->getType()->getName())) { + $instance->{$properties[$index]->name} = $properties[$index]->getType()->getName()::tryfrom($value); + } else { + $instance->{$properties[$index]->name} = $value; + } } else { - $instance->$key = $value; + $instance->{static::snakeCaseToCamelCase($key)} = $value; } } @@ -286,17 +292,15 @@ class Model $result = []; foreach ($properties as $property) { - $result[$property->name] = isset($this->{$property->name}) - ? $this->{$property->name} : null; - } - - foreach (static::$ignoreSave as $del) { - unset($result[$del]); + if (!in_array($property->name, static::$ignoreSave)) { + $result[$this->camelCaseToSnakeCase($property->name)] = isset($this->{$property->name}) + ? $this->{$property->name} : null; + } } foreach (static::$forceSave as $value) { $result[$value] = isset($this->$value) - ? $this->$value : null; + ? $this->$value : null; } foreach ($result as $i => $property) { @@ -305,10 +309,12 @@ class Model } if ($property instanceof \UnitEnum) { - $result[$i] = $property->value; + $result[$i] = $property->value ?? $property->name; } } + print_r($result); + return $result; } @@ -316,7 +322,7 @@ class Model * Devuelve el nombre de la clase actual aunque sea una clase extendida. * * @return string - * Devuelve el nombre de la clase actual. + * */ public static function className(): string { @@ -339,13 +345,39 @@ class Model return static::$table; } + return static::camelCaseToSnakeCase(static::className()) . static::$tableSufix; + } + + /** + * Convierte de lowerCamelCase a snake_case + * + * @param string $string + * + * @return string + */ + protected static function camelCaseToSnakeCase(string $string): string + { return strtolower( preg_replace( '/(?