[CORE][Entity] Fix implementation of createOrUpdate so it doesn't throw NotFoundException if trying to create an object

This was previously done because we wanted to notify the callee that
and entity existed but not with the provided contents. With the change
of return value, with a bool $is_update, this is no longer a problem.
This commit is contained in:
Hugo Sales 2021-08-07 18:19:01 +00:00 committed by Diogo Peralta Cordeiro
parent 4266b361c0
commit 71b1ee7796
Signed by: diogo
GPG Key ID: 18D2D35001FBFAB0

View File

@ -63,7 +63,7 @@ abstract class Entity
foreach ($args as $prop => $val) { foreach ($args as $prop => $val) {
if (property_exists($class, $prop)) { if (property_exists($class, $prop)) {
$set = 'set' . Formatting::snakeCaseToCamelCase($prop); $set = 'set' . ucfirst(Formatting::snakeCaseToCamelCase($prop));
$obj->{$set}($val); $obj->{$set}($val);
} else { } else {
Log::error($m = "Property {$class}::{$prop} doesn't exist"); Log::error($m = "Property {$class}::{$prop} doesn't exist");
@ -75,12 +75,22 @@ abstract class Entity
/** /**
* Create a new instance, but check for duplicates * Create a new instance, but check for duplicates
*
* @return [$obj, $is_update]
*/ */
public static function createOrUpdate(array $args, array $find_by_keys = []) public static function createOrUpdate(array $args, array $find_by_keys = [])
{ {
$table = DB::getTableForClass(get_called_class()); $table = DB::getTableForClass(get_called_class());
$find_by = $find_by_keys == [] ? $args : array_intersect_key($args, array_flip($find_by_keys)); $find_by = $find_by_keys == [] ? $args : array_intersect_key($args, array_flip($find_by_keys));
return self::create($args, DB::findOneBy($table, $find_by)); try {
$obj = DB::findOneBy($table, $find_by);
} catch (NotFoundException) {
$obj = null;
} catch (\Exception $e) {
Log::unexpected_exception($e);
}
$is_update = $obj !== null;
return [self::create($args, $obj), $is_update];
} }
/** /**