[ENTITY] Fixup implementation, as imformed by tests

This commit is contained in:
Hugo Sales 2021-07-21 16:41:21 +00:00
parent df956a5f90
commit 88bb0c6b38
Signed by untrusted user: someonewithpc
GPG Key ID: 7D0C7EAFC9D835A0

View File

@ -54,13 +54,20 @@ abstract class Entity
{ {
$class = get_called_class(); $class = get_called_class();
$obj = $obj ?: new $class(); $obj = $obj ?: new $class();
$args['created'] = $args['modified'] = new DateTime(); $date = new DateTime();
foreach (['created', 'modified'] as $prop) {
if (property_exists($class, $prop)) {
$args[$prop] = $date;
}
}
foreach ($args as $prop => $val) { foreach ($args as $prop => $val) {
if (property_exists($class, $prop) && $val != null) { if (property_exists($class, $prop) && $val != null) {
$set = 'set' . Formatting::snakeCaseToCamelCase($prop); $set = 'set' . Formatting::snakeCaseToCamelCase($prop);
$obj->{$set}($val); $obj->{$set}($val);
} else { } else {
Log::error("Property {$class}::{$prop} doesn't exist"); Log::error($m = "Property {$class}::{$prop} doesn't exist");
throw new \InvalidArgumentException($m);
} }
} }
return $obj; return $obj;
@ -69,40 +76,35 @@ abstract class Entity
/** /**
* Create a new instance, but check for duplicates * Create a new instance, but check for duplicates
*/ */
public static function createOrUpdate(array $args, array $find_by) public static function createOrUpdate(array $args, array $find_by_keys = [])
{ {
$table = Formatting::camelCaseToSnakeCase(get_called_class()); $table = DB::getTableForClass(get_called_class());
$find_by = $find_by_keys == [] ? $args : array_intersect_key($args, array_flip($find_by_keys));
return self::create($args, DB::findOneBy($table, $find_by)); return self::create($args, DB::findOneBy($table, $find_by));
} }
/** /**
* Remove a given $obj or whatever is found by `DB::findBy(..., $args)` * Get an Entity from its primary key
* from the database. Doesn't flush
*
* @param null|mixed $obj
*/
public static function remove(array $args, $obj = null)
{
$class = '\\' . get_called_class();
if ($obj == null) {
$obj = DB::findBy($class, $args);
}
DB::remove($obj);
}
/**
* Get an Entity from its id
* *
* @param int $id * @param int $id
* *
* @return null|static * @return null|static
*/ */
public static function getFromId(int $id): ?self public static function getWithPK(mixed $values): ?self
{ {
$array = explode('\\', get_called_class()); $values = is_array($values) ? $values : [$values];
$class = end($array); $class = get_called_class();
$keys = DB::getPKForClass($class);
$find_by = [];
foreach ($values as $k => $v) {
if (is_string($k)) {
$find_by[$k] = $v;
} else {
$find_by[$keys[$k]] = $v;
}
}
try { try {
return DB::findOneBy($class, ['id' => $id]); return DB::findOneBy($class, $find_by);
} catch (NotFoundException $e) { } catch (NotFoundException $e) {
return null; return null;
} }