[DATABASE] Refactor DB.php and make findBy always return an array, instead of a doctrine collection

This commit is contained in:
Hugo Sales 2020-07-25 17:49:57 +00:00 committed by Hugo Sales
parent 51f65edb55
commit d6a7843240
1 changed files with 6 additions and 10 deletions

View File

@ -70,30 +70,26 @@ abstract class DB
return $expressions; return $expressions;
} }
public static function findBy(string $table, array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null) public static function findBy(string $table, array $criteria, ?array $orderBy = null, ?int $limit = null, ?int $offset = null): array
{ {
$criteria = array_change_key_case($criteria); $criteria = array_change_key_case($criteria);
$ops = array_intersect(array_keys($criteria), self::$find_by_ops); $ops = array_intersect(array_keys($criteria), self::$find_by_ops);
$repo = self::__callStatic('getRepository', [$table]); $repo = self::getRepository($table);
if (empty($ops)) { if (empty($ops)) {
return $repo->findBy($criteria, $orderBy, $limit, $offset); return $repo->findBy($criteria, $orderBy, $limit, $offset);
} else { } else {
$criteria = new Criteria(self::buildExpression(Criteria::expr(), $criteria), $orderBy, $offset, $limit); $criteria = new Criteria(self::buildExpression(Criteria::expr(), $criteria), $orderBy, $offset, $limit);
return $repo->matching($criteria); return $repo->matching($criteria)->toArray(); // Always work with array or it becomes really complicated
} }
} }
public static function findOneBy(string $table, array $criteria, ?array $orderBy = null, ?int $offset = null) public static function findOneBy(string $table, array $criteria, ?array $orderBy = null, ?int $offset = null)
{ {
$res = self::findBy($table, $criteria, $orderBy, 1, $offset); $res = self::findBy($table, $criteria, $orderBy, 1, $offset);
if (is_array($res)) { if (count($res) == 1) {
if (count($res)) { return $res[0];
return $res[0];
} else {
throw new Exception("No value in table {$table} matches the requested criteria");
}
} else { } else {
return $res->first(); throw new Exception("No value in table {$table} matches the requested criteria");
} }
} }