Passed
Push — master ( 3fd861...81aaab )
by
unknown
15:54 queued 07:53
created

CStudentPublicationPostStateProcessor::process()   F

Complexity

Conditions 12
Paths 576

Size

Total Lines 75
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 42
nc 576
nop 4
dl 0
loc 75
rs 3.3888
c 0
b 0
f 0

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
namespace Chamilo\CoreBundle\State;
6
7
use ApiPlatform\Metadata\Operation;
8
use ApiPlatform\State\ProcessorInterface;
9
use Chamilo\CoreBundle\Entity\Course;
10
use Chamilo\CoreBundle\Entity\ResourceLink;
11
use Chamilo\CoreBundle\Entity\Session;
12
use Chamilo\CoreBundle\Entity\User;
13
use Chamilo\CoreBundle\Settings\SettingsManager;
14
use Chamilo\CourseBundle\Entity\CCalendarEvent;
15
use Chamilo\CourseBundle\Entity\CGroup;
16
use Chamilo\CourseBundle\Entity\CStudentPublication;
17
use Chamilo\CourseBundle\Entity\CStudentPublicationAssignment;
18
use DateTime;
19
use DateTimeZone;
20
use Doctrine\ORM\EntityManagerInterface;
21
use GradebookUtils;
22
use Symfony\Bundle\SecurityBundle\Security;
23
use Symfony\Component\Routing\RouterInterface;
24
use Symfony\Contracts\Translation\TranslatorInterface;
25
26
/**
27
 * @implements ProcessorInterface<CStudentPublication, CStudentPublication>
28
 */
29
final class CStudentPublicationPostStateProcessor implements ProcessorInterface
30
{
31
    public function __construct(
32
        private readonly ProcessorInterface $persistProcessor,
33
        private readonly EntityManagerInterface $entityManager,
34
        private readonly TranslatorInterface $translator,
35
        private readonly RouterInterface $router,
36
        private readonly Security $security,
37
        private readonly SettingsManager $settingsManager,
38
    ) {}
39
40
    public function process(
41
        $data,
42
        Operation $operation,
43
        array $uriVariables = [],
44
        array $context = []
45
    ): CStudentPublication {
46
        /** @var CStudentPublication $publication */
47
        $publication = $data;
48
49
        $result = $this->persistProcessor->process($publication, $operation, $uriVariables, $context);
50
51
        $assignment = $publication->getAssignment();
52
        $courseLink = $publication->getFirstResourceLink();
53
        $course = $courseLink->getCourse();
54
        $session = $courseLink->getSession();
55
        $group = $courseLink->getGroup();
56
57
        /** @var User $currentUser */
58
        $currentUser = $this->security->getUser();
59
60
        $isUpdate = $publication->getIid() !== null;
61
62
        if (!$assignment) {
63
            $assignment = new CStudentPublicationAssignment();
64
            $assignment->setPublication($publication);
65
            $publication->setAssignment($assignment);
66
            $this->entityManager->persist($assignment);
67
        }
68
69
        $payload = $context['request']->toArray();
70
71
        if (array_key_exists('qualification', $payload)) {
72
            $publication->setQualification((float) $payload['qualification']);
73
74
            $user = $this->security->getUser();
75
            if ($user instanceof User) {
76
                $publication->setQualificatorId($user->getId());
77
                $publication->setDateOfQualification(new \DateTime());
78
            }
79
        }
80
81
        if (isset($payload['expiresOn'])) {
82
            $assignment->setExpiresOn(new \DateTime($payload['expiresOn']));
83
        }
84
        if (isset($payload['endsOn'])) {
85
            $assignment->setEndsOn(new \DateTime($payload['endsOn']));
86
        }
87
88
        if (!$isUpdate || $publication->getQualification() > 0) {
89
            $assignment->setEnableQualification(true);
90
        }
91
92
        if ($publication->addToCalendar) {
93
            $event = $this->saveCalendarEvent($publication, $assignment, $courseLink, $course, $session, $group);
94
            $assignment->setEventCalendarId($event->getIid());
95
        } elseif (!$isUpdate) {
96
            $assignment->setEventCalendarId(0);
97
        }
98
99
        if ($assignment->getIid() !== null) {
100
            $publication->setHasProperties($assignment->getIid());
101
        }
102
        $publication
103
            ->setViewProperties(true)
104
            ->setUser($currentUser);
105
106
        $this->entityManager->flush();
107
108
        $this->saveGradebookConfig($publication, $course, $session);
109
110
        if (!$isUpdate) {
111
            $this->sendEmailAlertStudentsOnNewHomework($publication, $course, $session);
112
        }
113
114
        return $result;
115
    }
116
117
    private function saveCalendarEvent(
118
        CStudentPublication $publication,
119
        CStudentPublicationAssignment $assignment,
120
        ResourceLink $courseLink,
121
        Course $course,
122
        ?Session $session,
123
        ?CGroup $group,
124
    ): CCalendarEvent {
125
        $eventTitle = \sprintf(
126
            $this->translator->trans('Handing over of task %s'),
127
            $publication->getTitle()
128
        );
129
130
        $publicationUrl = $this->router->generate(
131
            'legacy_main',
132
            [
133
                'name' => 'work/work_list.php',
134
                'cid' => $course->getId(),
135
                'sid' => $session?->getId(),
136
                'gid' => $group?->getIid(),
137
                'id' => $publication->getIid(),
138
            ]
139
        );
140
141
        $content = \sprintf(
142
            '<div><a href="%s">%s</a></div> %s',
143
            $publicationUrl,
144
            $publication->getTitle(),
145
            $publication->getDescription()
146
        );
147
148
        $startDate = new DateTime('now', new DateTimeZone('UTC'));
149
        $endDate = new DateTime('now', new DateTimeZone('UTC'));
150
151
        if ($expiresOn = $assignment->getExpiresOn()) {
152
            $startDate = clone $expiresOn;
153
            $endDate = clone $expiresOn;
154
        }
155
156
        $color = CCalendarEvent::COLOR_STUDENT_PUBLICATION;
157
158
        if ($agendaColors = $this->settingsManager->getSetting('agenda.agenda_colors')) {
159
            $color = $agendaColors['student_publication'];
160
        }
161
162
        $event = (new CCalendarEvent())
163
            ->setTitle($eventTitle)
164
            ->setContent($content)
165
            ->setParent($course)
166
            ->setCreator($publication->getCreator())
167
            ->addLink(clone $courseLink)
168
            ->setStartDate($startDate)
169
            ->setEndDate($endDate)
170
            ->setColor($color)
171
        ;
172
173
        $this->entityManager->persist($event);
174
        $this->entityManager->flush();
175
176
        return $event;
177
    }
178
179
    private function saveGradebookConfig(CStudentPublication $publication, Course $course, ?Session $session): void
180
    {
181
        if ($publication->gradebookCategoryId <= 0) {
182
            return;
183
        }
184
185
        $gradebookLinkInfo = GradebookUtils::isResourceInCourseGradebook(
186
            $course->getId(),
187
            LINK_STUDENTPUBLICATION,
188
            $publication->getIid(),
189
            $session?->getId()
190
        );
191
192
        $linkId = empty($gradebookLinkInfo) ? null : $gradebookLinkInfo['id'];
193
194
        if ($publication->addToGradebook) {
195
            if (empty($linkId)) {
196
                GradebookUtils::add_resource_to_course_gradebook(
197
                    $publication->gradebookCategoryId,
198
                    $course->getId(),
199
                    LINK_STUDENTPUBLICATION,
200
                    $publication->getIid(),
201
                    $publication->getTitle(),
202
                    $publication->getWeight(),
203
                    $publication->getQualification(),
204
                    $publication->getDescription(),
205
                    1,
206
                    $session?->getId()
207
                );
208
            } else {
209
                GradebookUtils::updateResourceFromCourseGradebook(
210
                    $linkId,
211
                    $course->getId(),
212
                    $publication->getWeight()
213
                );
214
            }
215
        } else {
216
            // Delete everything of the gradebook for this $linkId
217
            GradebookUtils::remove_resource_from_course_gradebook($linkId);
218
        }
219
    }
220
221
    private function sendEmailAlertStudentsOnNewHomework(
222
        CStudentPublication $publication,
223
        Course $course,
224
        ?Session $session
225
    ): void {
226
        $sendEmailAlert = api_get_course_setting('email_alert_students_on_new_homework');
227
228
        switch ($sendEmailAlert) {
229
            case 1:
230
                sendEmailToStudentsOnHomeworkCreation(
231
                    $publication->getIid(),
232
                    $course->getId(),
233
                    $session?->getId()
234
                );
235
236
                // no break
237
            case 2:
238
                sendEmailToDrhOnHomeworkCreation(
239
                    $publication->getIid(),
240
                    $course->getId(),
241
                    $session?->getId()
242
                );
243
244
                break;
245
        }
246
    }
247
}
248