CStudentPublicationPostStateProcessor::process()   F
last analyzed

Complexity

Conditions 12
Paths 576

Size

Total Lines 76
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 42
nc 576
nop 4
dl 0
loc 76
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 = null !== $publication->getIid();
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 (null !== $assignment->getIid()) {
100
            $publication->setHasProperties($assignment->getIid());
101
        }
102
        $publication
103
            ->setViewProperties(true)
104
            ->setUser($currentUser)
105
        ;
106
107
        $this->entityManager->flush();
108
109
        $this->saveGradebookConfig($publication, $course, $session);
110
111
        if (!$isUpdate) {
112
            $this->sendEmailAlertStudentsOnNewHomework($publication, $course, $session);
113
        }
114
115
        return $result;
116
    }
117
118
    private function saveCalendarEvent(
119
        CStudentPublication $publication,
120
        CStudentPublicationAssignment $assignment,
121
        ResourceLink $courseLink,
122
        Course $course,
123
        ?Session $session,
124
        ?CGroup $group,
125
    ): CCalendarEvent {
126
        $eventTitle = \sprintf(
127
            $this->translator->trans('Handing over of task %s'),
128
            $publication->getTitle()
129
        );
130
131
        $publicationUrl = $this->router->generate(
132
            'legacy_main',
133
            [
134
                'name' => 'work/work_list.php',
135
                'cid' => $course->getId(),
136
                'sid' => $session?->getId(),
137
                'gid' => $group?->getIid(),
138
                'id' => $publication->getIid(),
139
            ]
140
        );
141
142
        $content = \sprintf(
143
            '<div><a href="%s">%s</a></div> %s',
144
            $publicationUrl,
145
            $publication->getTitle(),
146
            $publication->getDescription()
147
        );
148
149
        $startDate = new DateTime('now', new DateTimeZone('UTC'));
150
        $endDate = new DateTime('now', new DateTimeZone('UTC'));
151
152
        if ($expiresOn = $assignment->getExpiresOn()) {
153
            $startDate = clone $expiresOn;
154
            $endDate = clone $expiresOn;
155
        }
156
157
        $color = CCalendarEvent::COLOR_STUDENT_PUBLICATION;
158
159
        if ($agendaColors = $this->settingsManager->getSetting('agenda.agenda_colors')) {
160
            $color = $agendaColors['student_publication'];
161
        }
162
163
        $event = (new CCalendarEvent())
164
            ->setTitle($eventTitle)
165
            ->setContent($content)
166
            ->setParent($course)
167
            ->setCreator($publication->getCreator())
168
            ->addLink(clone $courseLink)
169
            ->setStartDate($startDate)
170
            ->setEndDate($endDate)
171
            ->setColor($color)
172
        ;
173
174
        $this->entityManager->persist($event);
175
        $this->entityManager->flush();
176
177
        return $event;
178
    }
179
180
    private function saveGradebookConfig(CStudentPublication $publication, Course $course, ?Session $session): void
181
    {
182
        if ($publication->gradebookCategoryId <= 0) {
183
            return;
184
        }
185
186
        $gradebookLinkInfo = GradebookUtils::isResourceInCourseGradebook(
187
            $course->getId(),
188
            LINK_STUDENTPUBLICATION,
189
            $publication->getIid(),
190
            $session?->getId()
191
        );
192
193
        $linkId = empty($gradebookLinkInfo) ? null : $gradebookLinkInfo['id'];
194
195
        if ($publication->addToGradebook) {
196
            if (empty($linkId)) {
197
                GradebookUtils::add_resource_to_course_gradebook(
198
                    $publication->gradebookCategoryId,
199
                    $course->getId(),
200
                    LINK_STUDENTPUBLICATION,
201
                    $publication->getIid(),
202
                    $publication->getTitle(),
203
                    $publication->getWeight(),
204
                    $publication->getQualification(),
205
                    $publication->getDescription(),
206
                    1,
207
                    $session?->getId()
208
                );
209
            } else {
210
                GradebookUtils::updateResourceFromCourseGradebook(
211
                    $linkId,
212
                    $course->getId(),
213
                    $publication->getWeight()
214
                );
215
            }
216
        } else {
217
            // Delete everything of the gradebook for this $linkId
218
            GradebookUtils::remove_resource_from_course_gradebook($linkId);
219
        }
220
    }
221
222
    private function sendEmailAlertStudentsOnNewHomework(
223
        CStudentPublication $publication,
224
        Course $course,
225
        ?Session $session
226
    ): void {
227
        $sendEmailAlert = api_get_course_setting('email_alert_students_on_new_homework');
228
229
        switch ($sendEmailAlert) {
230
            case 1:
231
                sendEmailToStudentsOnHomeworkCreation(
232
                    $publication->getIid(),
233
                    $course->getId(),
234
                    $session?->getId()
235
                );
236
237
                // no break
238
            case 2:
239
                sendEmailToDrhOnHomeworkCreation(
240
                    $publication->getIid(),
241
                    $course->getId(),
242
                    $session?->getId()
243
                );
244
245
                break;
246
        }
247
    }
248
}
249