mirror of
https://gitlab.com/Chill-Projet/chill-bundles.git
synced 2026-03-03 04:29:40 +00:00
Refactor AuditTrailRepository to extract query-building logic and add support for date and subject-based filtering
- Moved query-building logic to a new `buildByCriteriaQuery` private method for better modularity. - Added handling for `from_date`, `to_date`, and subject-based filtering using `JSONB` containment for improved query flexibility.
This commit is contained in:
@@ -11,9 +11,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace Chill\MainBundle\Repository;
|
||||
|
||||
use Chill\MainBundle\Audit\Subject;
|
||||
use Chill\MainBundle\Entity\AuditTrail;
|
||||
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
|
||||
use Doctrine\DBAL\Types\Types;
|
||||
use Doctrine\ORM\QueryBuilder;
|
||||
use Doctrine\Persistence\ManagerRegistry;
|
||||
|
||||
/**
|
||||
@@ -65,10 +67,44 @@ class AuditTrailRepository extends ServiceEntityRepository
|
||||
*/
|
||||
public function findByCriteria(array $criteria, int $offset = 0, int $limit = 100): array
|
||||
{
|
||||
return $this->createQueryBuilder('audit')
|
||||
return $this->buildByCriteriaQuery($criteria)
|
||||
->orderBy('audit.occurredAt', 'DESC')
|
||||
->setMaxResults($limit)
|
||||
->setFirstResult($offset)
|
||||
->getQuery()->getResult();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{subjects?: list<Subject>, from_date?: \DateTimeImmutable, to_date?: \DateTimeImmutable} $criteria
|
||||
*/
|
||||
private function buildByCriteriaQuery(array $criteria): QueryBuilder
|
||||
{
|
||||
$qb = $this->createQueryBuilder('audit');
|
||||
|
||||
if (null !== $fromDate = $criteria['from_date'] ?? null) {
|
||||
$qb->andWhere('audit.occurredAt >= :from_date');
|
||||
$qb->setParameter('from_date', $fromDate);
|
||||
}
|
||||
|
||||
if (null !== $toDate = $criteria['to_date'] ?? null) {
|
||||
$qb->andWhere('audit.occurredAt <= :to_date');
|
||||
$qb->setParameter('to_date', $toDate);
|
||||
}
|
||||
|
||||
if ([] !== $subjects = $criteria['subjects'] ?? []) {
|
||||
$orx = $qb->expr()->orX();
|
||||
$k = 0;
|
||||
foreach ($subjects as $subject) {
|
||||
$orx->add($qb->expr()->eq('audit.mainSubject', ':subject_'.$k));
|
||||
$qb->setParameter('subject_'.$k, $subject->asArray(), Types::JSON);
|
||||
++$k;
|
||||
$orx->add('TRUE = JSONB_CONTAINS(audit.subjects, :subject_'.$k.')');
|
||||
$qb->setParameter('subject_'.$k, [$subject->asArray()], Types::JSON);
|
||||
++$k;
|
||||
}
|
||||
$qb->andWhere($orx);
|
||||
}
|
||||
|
||||
return $qb;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user