|
| 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 | +} |
0 commit comments