[DB] Handle using methods with class name as well as table name and add lookup methods

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

View File

@ -34,7 +34,6 @@ namespace App\Core\DB;
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 Doctrine\Common\Collections\Criteria; use Doctrine\Common\Collections\Criteria;
use Doctrine\Common\Collections\Expr\Expression; use Doctrine\Common\Collections\Expr\Expression;
use Doctrine\Common\Collections\ExpressionBuilder; use Doctrine\Common\Collections\ExpressionBuilder;
@ -55,14 +54,26 @@ abstract class DB
* Table name to class map, used to allow specifying table names instead of classes in doctrine calls * Table name to class map, used to allow specifying table names instead of classes in doctrine calls
*/ */
private static array $table_map = []; private static array $table_map = [];
private static array $class_pk = [];
public static function initTableMap() public static function initTableMap()
{ {
$all = self::$em->getMetadataFactory()->getAllMetadata(); $all = self::$em->getMetadataFactory()->getAllMetadata();
foreach ($all as $meta) { foreach ($all as $meta) {
self::$table_map[$meta->getTableName()] = $meta->getMetadataValue('name'); self::$table_map[$meta->getTableName()] = $meta->getMetadataValue('name');
self::$class_pk[$meta->getMetadataValue('name')] = $meta->getIdentifier();
} }
} }
public static function getTableForClass(string $class)
{
return array_search($class, self::$table_map);
}
public static function getPKForClass(string $class)
{
return self::$class_pk[$class];
}
/** /**
* Perform a Doctrine Query Language query * Perform a Doctrine Query Language query
*/ */
@ -208,7 +219,7 @@ abstract class DB
public static function __callStatic(string $name, array $args) public static function __callStatic(string $name, array $args)
{ {
if (in_array($name, ['find', 'getReference', 'getPartialReference', 'getRepository']) if (in_array($name, ['find', 'getReference', 'getPartialReference', 'getRepository'])
&& !Formatting::startsWith($args[0], '\\')) { && !str_contains($args[0], '\\')) {
$args[0] = self::$table_map[$args[0]]; $args[0] = self::$table_map[$args[0]];
} }