Passed
Push — master ( 5330e2...bd7dad )
by Yannick
09:55
created

CDropboxCategoryRepository   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A createForUser() 0 24 1
A findByContextAndArea() 0 14 3
A __construct() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CourseBundle\Repository;
8
9
use Chamilo\CoreBundle\Repository\ResourceRepository;
10
use Chamilo\CourseBundle\Entity\CDropboxCategory;
11
use Doctrine\Persistence\ManagerRegistry;
12
13
/**
14
 * Custom queries for Dropbox categories.
15
 */
16
final class CDropboxCategoryRepository extends ResourceRepository
17
{
18
    public function __construct(ManagerRegistry $registry)
19
    {
20
        parent::__construct($registry, CDropboxCategory::class);
21
    }
22
23
    /**
24
     * Find categories scoped by course, session, user and area (sent|received).
25
     */
26
    public function findByContextAndArea(int $cid, ?int $sid, int $uid, string $area): array
27
    {
28
        $qb = $this->createQueryBuilder('c')
29
            ->andWhere('c.cId = :cid')->setParameter('cid', $cid)
30
            ->andWhere('c.sessionId = :sid')->setParameter('sid', $sid ?? 0)
31
            ->andWhere('c.userId = :uid')->setParameter('uid', $uid);
32
33
        if ($area === 'sent') {
34
            $qb->andWhere('c.sent = true');
35
        } elseif ($area === 'received') {
36
            $qb->andWhere('c.received = true');
37
        }
38
39
        return $qb->orderBy('c.title', 'ASC')->getQuery()->getResult();
40
    }
41
42
    /**
43
     * Create a category for the given user/context and mirror cat_id = iid
44
     * Uses two flushes to first get autoincrement iid, then align cat_id without raw SQL.
45
     */
46
    public function createForUser(int $cid, ?int $sid, int $uid, string $title, string $area): CDropboxCategory
47
    {
48
        $em = $this->getEntityManager();
49
50
        $cat = new CDropboxCategory();
51
        $cat->setCId($cid);
52
        $cat->setSessionId($sid ?? 0);
53
        $cat->setUserId($uid);
54
        $cat->setTitle($title);
55
        $cat->setReceived($area === 'received');
56
        $cat->setSent($area === 'sent');
57
        $cat->setCatId(0); // will be mirrored to iid after first flush
58
59
        // 1st flush: ensure iid is generated.
60
        $em->persist($cat);
61
        $em->flush();
62
63
        // Mirror cat_id = iid safely.
64
        $cat->setCatId((int) $cat->getIid());
65
66
        // 2nd flush: persist alignment.
67
        $em->flush();
68
69
        return $cat;
70
    }
71
}
72