Passed
Push — master ( d4517f...26a928 )
by Yannick
08:22
created

GetCourseStatsAction::__invoke()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 26
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 4
nop 3
dl 0
loc 26
rs 9.4888
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
declare(strict_types=1);
5
6
namespace Chamilo\CoreBundle\Controller\Api;
7
8
use Chamilo\CoreBundle\Entity\Course;
9
use Chamilo\CoreBundle\Repository\Node\CourseRepository;
10
use Chamilo\CoreBundle\Repository\SessionRepository;
11
use Chamilo\CoreBundle\Helpers\TrackingStatsHelper;
12
use Symfony\Component\HttpFoundation\JsonResponse;
13
use Symfony\Component\HttpFoundation\Request;
14
use Symfony\Component\HttpKernel\Attribute\AsController;
15
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
16
17
#[AsController]
18
final class GetCourseStatsAction
19
{
20
    public function __construct(
21
        private readonly CourseRepository $courseRepo,
22
        private readonly SessionRepository $sessionRepo,
23
        private readonly TrackingStatsHelper $statsHelper,
24
    ) {}
25
26
    public function __invoke(int $id, string $metric, Request $request): JsonResponse
27
    {
28
        /* @var Course $course */
29
        $course = $this->courseRepo->find($id);
30
        if (!$course) {
0 ignored issues
show
introduced by
$course is of type Chamilo\CoreBundle\Entity\Course, thus it always evaluated to true.
Loading history...
31
            throw new NotFoundHttpException('Course not found.');
32
        }
33
34
        // Optional session
35
        $session = null;
36
        $sessionId = $request->query->getInt('sessionId') ?: null;
37
        if ($sessionId) {
38
            $session = $this->sessionRepo->find($sessionId);
39
            if (!$session) {
40
                throw new NotFoundHttpException('Session not found.');
41
            }
42
        }
43
44
        // Switch by metric
45
        $payload = match ($metric) {
46
            'course-avg-score'    => $this->statsHelper->getCourseAverageScore($course, $session),
47
            'course-avg-progress' => $this->statsHelper->getCourseAverageProgress($course, $session),
48
            default               => throw new NotFoundHttpException('Metric not supported.'),
49
        };
50
51
        return new JsonResponse($payload, 200);
52
    }
53
}
54