Convert object/database naming conventions.

Adhere to PSR-12 by converting object properties to "lowerCamelCase" for objects
and "snake_case" for database interactions.

Backward compatibility is maintained: object properties already using
"snake_case" will continue to work without issue.
This commit is contained in:
kj
2025-09-07 15:01:45 -03:00
parent c9f467345b
commit b282d5479f

View File

@ -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->$key = $value;
$instance->{$properties[$index]->name} = $value;
}
} else {
$instance->{static::snakeCaseToCamelCase($key)} = $value;
}
}
@ -286,12 +292,10 @@ class Model
$result = [];
foreach ($properties as $property) {
$result[$property->name] = isset($this->{$property->name})
if (!in_array($property->name, static::$ignoreSave)) {
$result[$this->camelCaseToSnakeCase($property->name)] = isset($this->{$property->name})
? $this->{$property->name} : null;
}
foreach (static::$ignoreSave as $del) {
unset($result[$del]);
}
foreach (static::$forceSave as $value) {
@ -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(
'/(?<!^)[A-Z]/',
'_$0',
static::className()
$string
)
) . static::$tableSufix;
);
}
/**
* Convierte de snake_case a lowerCamelCase
*
* @param string $string
*
* @return string
*/
protected static function snakeCaseToCamelCase(string $string): string
{
return preg_replace_callback('/_([a-z])/', function ($matches) {
return strtoupper($matches[1]);
}, $string);
}
/**