Passed
Push — master ( 03c86d...7dc071 )
by
unknown
21:41 queued 11:00
created

CStudentPublicationPostStateProcessor::process()   B

Complexity

Conditions 9
Paths 96

Size

Total Lines 63
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 35
c 0
b 0
f 0
nc 96
nop 4
dl 0
loc 63
rs 8.0555

How to fix   Long Method   

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