Passed
Push — master ( b36cbe...35a819 )
by Angel Fernando Quiroz
09:33
created

UserRelCourseVoteRepository   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
dl 0
loc 47
rs 10
c 1
b 0
f 0
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getCouseRating() 0 34 3
A __construct() 0 3 1
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\Repository;
8
9
use Chamilo\CoreBundle\Entity\Course;
10
use Chamilo\CoreBundle\Entity\Session;
11
use Chamilo\CoreBundle\Entity\UserRelCourseVote;
12
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
13
use Doctrine\DBAL\ParameterType;
14
use Doctrine\ORM\NonUniqueResultException;
15
use Doctrine\ORM\NoResultException;
16
use Doctrine\Persistence\ManagerRegistry;
17
18
/**
19
 * @extends ServiceEntityRepository<UserRelCourseVote>
20
 */
21
class UserRelCourseVoteRepository extends ServiceEntityRepository
22
{
23
    public function __construct(ManagerRegistry $registry)
24
    {
25
        parent::__construct($registry, UserRelCourseVote::class);
26
    }
27
28
    /**
29
     * Retrieves the average vote and the count of votes for a specific course.
30
     *
31
     * @return array The first element of the array is the average vote (rounded to 2 decimal places),
32
     *               and the second element is the count of votes.
33
     */
34
    public function getCouseRating(Course $course, ?Session $session = null): array
35
    {
36
        $qb = $this->createQueryBuilder('v');
37
38
        $qb
39
            ->select([
40
                $qb->expr()->avg('v.vote'),
41
                $qb->expr()->count('v.id')
42
            ])
43
            ->where($qb->expr()->eq('v.course', ':course'))
44
            ->setParameter('course', $course->getId(), ParameterType::INTEGER)
45
        ;
46
47
        if ($session !== null) {
48
            $qb
49
                ->andWhere($qb->expr()->eq('v.session', ':session'))
50
                ->setParameter('session', $session->getId(), ParameterType::INTEGER)
51
            ;
52
        } else {
53
            $qb->andWhere($qb->expr()->isNull('v.session'));
54
        }
55
56
        try {
57
            $result = $qb
58
                ->setMaxResults(1)
59
                ->getQuery()
60
                ->getSingleResult();
61
        } catch (NoResultException|NonUniqueResultException) {
62
            $result = [1 => 0, 2 => 0];
63
        }
64
65
        return [
66
            'average' => round((float) $result[1], 2),
67
            'count' => $result[2]
68
        ];
69
    }
70
}
71