[CORE][DB] Add DB::refetch, which refetches an entity from the database, so it's managed and definitely up to date (use when wanting to update entities from cache)

This commit is contained in:
Hugo Sales 2022-03-31 03:25:56 +01:00
parent 20e07c9140
commit ded9c86054
No known key found for this signature in database
GPG Key ID: 7D0C7EAFC9D835A0

View File

@ -36,6 +36,7 @@ namespace App\Core;
use App\Util\Exception\DuplicateFoundException; use App\Util\Exception\DuplicateFoundException;
use App\Util\Exception\NotFoundException; use App\Util\Exception\NotFoundException;
use App\Util\Formatting;
use Closure; use Closure;
use Doctrine\Common\Collections\Criteria; use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\ExpressionBuilder; use Doctrine\Common\Collections\ExpressionBuilder;
@ -109,7 +110,7 @@ class DB
return array_search($class, self::$table_map); return array_search($class, self::$table_map);
} }
public static function getPKForClass(string $class) public static function getPKForClass(string $class): array
{ {
return self::$class_pk[$class]; return self::$class_pk[$class];
} }
@ -162,7 +163,7 @@ class DB
fn ($p) => (fn ($o) => $o instanceof $aliases[$p]), fn ($p) => (fn ($o) => $o instanceof $aliases[$p]),
), ),
); );
} else if (($options['limit'] ?? null) === 1) { } elseif (($options['limit'] ?? null) === 1) {
return $results[0] ?? null; return $results[0] ?? null;
} else { } else {
return $results; return $results;
@ -320,6 +321,17 @@ class DB
return $id; return $id;
} }
public static function refetch(Entity $ent): ?Entity
{
$pks = self::getPKForClass($ent::class);
$criteria = [];
foreach ($pks as $pk) {
$method = Formatting::snakeCaseToCamelCase("get_{$pk}");
$criteria[$pk] = $ent->{$method}();
}
return self::findOneBy($ent::class, $criteria);
}
/** /**
* Intercept static function calls to allow referring to entities * Intercept static function calls to allow referring to entities
* without writing the namespace (which is deduced from the call * without writing the namespace (which is deduced from the call