Passed
Pull Request — master (#7085)
by
unknown
10:19
created

UserRelCourseVoteHelper::getCourseRating()   A

Complexity

Conditions 5
Paths 16

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
c 1
b 0
f 0
nc 16
nop 2
dl 0
loc 22
rs 9.4888
1
<?php
2
declare(strict_types=1);
3
4
namespace Chamilo\CoreBundle\Helpers;
5
6
7
use Chamilo\CoreBundle\Entity\Course;
8
use Chamilo\CoreBundle\Entity\Session;
9
use Chamilo\CoreBundle\Entity\UserRelCourseVote;
10
use Doctrine\DBAL\ParameterType;
11
use Doctrine\ORM\EntityManagerInterface;
12
13
class UserRelCourseVoteHelper
14
{
15
    public function __construct(private readonly EntityManagerInterface $em) {}
16
17
18
    public function getCourseRating(Course $course, ?Session $session = null): array
19
    {
20
        $qb = $this->em->createQueryBuilder()
21
            ->select('AVG(v.vote) AS avgVote', 'COUNT(v.id) AS countVotes')
22
            ->from(UserRelCourseVote::class, 'v')
23
            ->where('v.course = :course')
24
            ->setParameter('course', $course->getId(), ParameterType::INTEGER);
25
26
27
        if ($session !== null) {
28
            $qb->andWhere('v.session = :session')
29
                ->setParameter('session', $session->getId(), ParameterType::INTEGER);
30
        } else {
31
            $qb->andWhere('v.session IS NULL');
32
        }
33
34
35
        $row = $qb->getQuery()->getSingleResult();
36
        $avg = isset($row['avgVote']) && $row['avgVote'] !== null ? round((float) $row['avgVote'], 2) : 0.0;
37
        $count = isset($row['countVotes']) ? (int) $row['countVotes'] : 0;
38
39
        return ['avg' => $avg, 'average' => $avg, 'count' => $count];
40
41
42
    }
43
}
44