Passed
Push — master ( 689c60...4980bd )
by Julito
09:36
created

SysAnnouncementRepository::getAnnouncements()   C

Complexity

Conditions 16
Paths 4

Size

Total Lines 84
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 16
eloc 46
c 0
b 0
f 0
nc 4
nop 3
dl 0
loc 84
rs 5.5666

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/* For licensing terms, see /license.txt */
6
7
namespace Chamilo\CoreBundle\Repository;
8
9
use Chamilo\CoreBundle\Entity\AccessUrl;
10
use Chamilo\CoreBundle\Entity\Session;
11
use Chamilo\CoreBundle\Entity\SessionRelUser;
12
use Chamilo\CoreBundle\Entity\SysAnnouncement;
13
use Chamilo\CoreBundle\Entity\User;
14
use Datetime;
15
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
16
use Doctrine\DBAL\Types\Types;
17
use Doctrine\ORM\QueryBuilder;
18
use Doctrine\Persistence\ManagerRegistry;
19
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
20
use Symfony\Component\Security\Core\Security;
21
22
class SysAnnouncementRepository extends ServiceEntityRepository
23
{
24
    protected ParameterBagInterface $parameterBag;
25
    protected Security $security;
26
27
    public function __construct(ManagerRegistry $registry, ParameterBagInterface $parameterBag, Security $security)
28
    {
29
        parent::__construct($registry, SysAnnouncement::class);
30
        $this->parameterBag = $parameterBag;
31
        $this->security = $security;
32
    }
33
34
    public function getVisibilityList()
35
    {
36
        $hierarchy = $this->parameterBag->get('security.role_hierarchy.roles');
37
        $roles = [];
38
        array_walk_recursive($hierarchy, function ($role) use (&$roles): void {
39
            $roles[$role] = $role;
40
        });
41
42
        return $roles;
43
    }
44
45
    public function getAnnouncementsQueryBuilder(string $iso, AccessUrl $url, ?User $user = null): QueryBuilder
46
    {
47
        $qb = $this->createQueryBuilder('s');
48
        $qb
49
            ->andWhere(' s.lang IS NULL OR s.lang = :iso')
50
            ->andWhere('s.url = :url')
51
            ->setParameters(
52
                ['url' => $url, 'iso' => $iso]
53
            )
54
        ;
55
56
        $this->addDateQueryBuilder($qb);
57
58
        if (null !== $user) {
59
            $this->addRoleListQueryBuilder($user->getRoles(), $qb);
60
        }
61
62
        $qb->orderBy('s.dateStart', 'DESC');
63
64
        return $qb;
65
    }
66
67
    public function getAnnouncements(User $user, AccessUrl $url, string $iso): array
68
    {
69
        $qb = $this->getAnnouncementsQueryBuilder($iso, $url, $user);
70
71
        $announcements = $qb->getQuery()->getResult();
72
        $cutSize = 500;
73
        $list = [];
74
        if (!empty($announcements)) {
75
            /** @var SysAnnouncement $announcement */
76
            foreach ($announcements as $announcement) {
77
                if ($announcement->hasCareer()) {
78
                    $promotionList = [];
79
                    if ($announcement->hasPromotion()) {
80
                        $promotionList[] = $announcement->getPromotion();
81
                    } else {
82
                        $promotionList = $announcement->getCareer()->getPromotions();
83
                    }
84
85
                    $show = false;
86
                    foreach ($promotionList as $promotion) {
87
                        $sessionList = $promotion->getSessions();
88
                        foreach ($sessionList as $session) {
89
                            $subscription = (new SessionRelUser())
90
                                ->setUser($user)
91
                                ->setSession($session)
92
                                ->setRelationType(0)
93
                            ;
94
95
                            // Check student
96
                            if ($this->security->isGranted('ROLE_STUDENT') &&
97
                                $session->hasUser($subscription)
98
                                //\SessionManager::isUserSubscribedAsStudent($sessionId, $userId)
99
                            ) {
100
                                $show = true;
101
102
                                break 2;
103
                            }
104
105
                            if ($this->security->isGranted('ROLE_TEACHER') &&
106
                                $session->isUserGeneralCoach($user)
107
                                //SessionManager::user_is_general_coach($userId, $sessionId)
108
                            ) {
109
                                $show = true;
110
111
                                break 2;
112
                            }
113
114
                            // Check course coach
115
                            //$coaches = \SessionManager::getCoachesBySession($sessionId);
116
                            if ($this->security->isGranted('ROLE_TEACHER') &&
117
                                $session->getSessionRelCourseByUser($user, Session::COACH)->count() > 0
118
                            ) {
119
                                $show = true;
120
121
                                break 2;
122
                            }
123
                        }
124
                    }
125
126
                    if (false === $show) {
127
                        continue;
128
                    }
129
                }
130
131
                $announcementData = [
132
                    'id' => $announcement->getId(),
133
                    'title' => $announcement->getTitle(),
134
                    'content' => $announcement->getContent(),
135
                    'readMore' => null,
136
                ];
137
138
                if (api_strlen(strip_tags($announcement->getContent())) > $cutSize) {
139
                    $announcementData['content'] = cut($announcement->getContent(), $cutSize);
140
                    $announcementData['readMore'] = true;
141
                }
142
                $list[] = $announcementData;
143
            }
144
        }
145
146
        if (0 === \count($list)) {
147
            return [];
148
        }
149
150
        return $list;
151
    }
152
153
    public function addRoleListQueryBuilder(array $roleList, QueryBuilder $qb = null): QueryBuilder
154
    {
155
        $qb = $this->getOrCreateQueryBuilder($qb, 's');
156
        if (!empty($roleList)) {
157
            $qb
158
                ->andWhere('s.roles IN (:roles) OR s.roles IN (:anon)')
159
                ->setParameter('roles', $roleList, Types::ARRAY)
160
                ->setParameter('anon', ['ROLE_ANONYMOUS'], Types::ARRAY)
161
            ;
162
        }
163
164
        return $qb;
165
    }
166
167
    public function addDateQueryBuilder(QueryBuilder $qb = null): QueryBuilder
168
    {
169
        $qb = $this->getOrCreateQueryBuilder($qb, 's');
170
        $qb
171
            ->andWhere('s.dateStart IS NULL OR s.dateEnd > :now')
172
            ->setParameter('now', new Datetime(), Types::DATETIME_MUTABLE)
173
        ;
174
175
        return $qb;
176
    }
177
178
    public function update(SysAnnouncement $sysAnnouncement, $andFlush = true): void
179
    {
180
        $this->getEntityManager()->persist($sysAnnouncement);
181
        if ($andFlush) {
182
            $this->getEntityManager()->flush();
183
        }
184
    }
185
186
    protected function getOrCreateQueryBuilder(QueryBuilder $qb = null, string $alias = 's'): QueryBuilder
187
    {
188
        return $qb ?: $this->createQueryBuilder($alias);
189
    }
190
}
191