Passed
Push — master ( af00ba...368e6c )
by
unknown
10:47
created

LpCollectionStateProvider::supports()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 1
nc 2
nop 3
dl 0
loc 3
rs 10
c 1
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\State;
8
9
use ApiPlatform\Metadata\Operation;
10
use ApiPlatform\State\ProviderInterface;
11
use Chamilo\CoreBundle\Entity\Course;
12
use Chamilo\CoreBundle\Entity\Session as CoreSession;
13
use Chamilo\CoreBundle\Entity\User;
14
use Chamilo\CourseBundle\Entity\CLp;
15
use Chamilo\CourseBundle\Repository\CLpRepository;
16
use Doctrine\ORM\EntityManagerInterface;
17
use Symfony\Bundle\SecurityBundle\Security;
18
19
final class LpCollectionStateProvider implements ProviderInterface
20
{
21
    public function __construct(
22
        private readonly EntityManagerInterface $em,
23
        private readonly CLpRepository $lpRepo,
24
        private readonly Security $security
25
    ) {}
26
27
    public function supports(Operation $op, array $uriVariables = [], array $ctx = []): bool
28
    {
29
        return $op->getClass() === CLp::class && $op->getName() === 'get_lp_collection_with_progress';
30
    }
31
32
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): object|array|null
33
    {
34
        $f = $context['filters'] ?? [];
35
        $parentNodeId = (int)($f['resourceNode.parent'] ?? 0);
36
        if ($parentNodeId <= 0) {
37
            return [];
38
        }
39
40
        $course = $this->em->createQuery(
41
            'SELECT c
42
               FROM ' . Course::class . ' c
43
               JOIN c.resourceNode rn
44
              WHERE rn.id = :nid'
45
        )
46
            ->setParameter('nid', $parentNodeId)
47
            ->getOneOrNullResult();
48
49
        if (!$course) {
50
            return [];
51
        }
52
53
        $sid   = isset($f['sid']) ? (int)$f['sid'] : null;
54
        $title = $f['title'] ?? null;
55
56
        $session = $sid ? $this->em->getReference(CoreSession::class, $sid) : null;
57
58
        $lps = $this->lpRepo->findAllByCourse($course, $session, $title)
59
            ->getQuery()
60
            ->getResult();
61
62
        if (!$lps) {
63
            return [];
64
        }
65
66
        $user = $this->security->getUser();
67
        if ($user instanceof User) {
68
            $progress = $this->lpRepo->lastProgressForUser($lps, $user, $session);
69
            foreach ($lps as $lp) {
70
                $lp->setProgress($progress[(int)$lp->getIid()] ?? 0);
71
            }
72
        }
73
74
        return $lps;
75
    }
76
}
77