Passed
Push — dependabot/npm_and_yarn/cross-... ( a16049...ad80c0 )
by
unknown
16:45 queued 07:24
created

TrackEDefaultRepository   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
eloc 31
c 4
b 0
f 1
dl 0
loc 49
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
B getUserCourseRegistrationAt() 0 39 7
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Repository;
8
9
use Chamilo\CoreBundle\Entity\TrackEDefault;
10
use DateTime;
11
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
12
use Doctrine\Persistence\ManagerRegistry;
13
14
class TrackEDefaultRepository extends ServiceEntityRepository
15
{
16
    public function __construct(ManagerRegistry $registry)
17
    {
18
        parent::__construct($registry, TrackEDefault::class);
19
    }
20
21
    /**
22
     * Retrieves the registration date of a user in a specific course or session.
23
     */
24
    public function getUserCourseRegistrationAt(int $courseId, int $userId, ?int $sessionId = 0): ?\DateTime
25
    {
26
        $serializedPattern = sprintf('s:2:"id";i:%d;', $userId);
27
28
        $qb = $this->createQueryBuilder('te')
29
            ->select('te.defaultDate')
30
            ->where('te.cId = :courseId')
31
            ->andWhere('te.defaultValueType = :valueType')
32
            ->andWhere('te.defaultEventType = :eventType')
33
            ->andWhere('te.defaultValue LIKE :serializedPattern')
34
            ->setParameter('courseId', $courseId)
35
            ->setParameter('valueType', 'user_object')
36
            ->setParameter('eventType', 'user_subscribed')
37
            ->setParameter('serializedPattern', '%' . $serializedPattern . '%');
38
39
        if ($sessionId > 0) {
40
            $qb->andWhere('te.sessionId = :sessionId')
41
                ->setParameter('sessionId', $sessionId);
42
        } elseif ($sessionId === 0) {
43
            $qb->andWhere('te.sessionId = 0');
44
        } else {
45
            $qb->andWhere('te.sessionId IS NULL');
46
        }
47
48
        $qb->setMaxResults(1);
49
        $query = $qb->getQuery();
50
51
        try {
52
            $result = $query->getOneOrNullResult();
53
            if ($result && isset($result['defaultDate'])) {
54
                return $result['defaultDate'] instanceof \DateTime
55
                    ? $result['defaultDate']
56
                    : new \DateTime($result['defaultDate']);
57
            }
58
        } catch (\Exception $e) {
59
            throw new \RuntimeException('Error fetching registration date: ' . $e->getMessage());
60
        }
61
62
        return null;
63
    }
64
}
65