Passed
Pull Request — master (#5710)
by
unknown
07:01
created

MessageProcessor::checkAndUpdateMessageStatus()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 7
nc 2
nop 1
dl 0
loc 14
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\State;
8
9
use ApiPlatform\Metadata\DeleteOperationInterface;
10
use ApiPlatform\Metadata\Operation;
11
use ApiPlatform\Metadata\Patch;
12
use ApiPlatform\State\ProcessorInterface;
13
use Chamilo\CoreBundle\Entity\Message;
14
use Chamilo\CoreBundle\Entity\MessageAttachment;
15
use Chamilo\CoreBundle\Entity\MessageRelUser;
16
use Chamilo\CoreBundle\Repository\ResourceNodeRepository;
17
use Doctrine\ORM\EntityManagerInterface;
18
use InvalidArgumentException;
19
use LogicException;
20
use Notification;
21
use Symfony\Bundle\SecurityBundle\Security;
22
use Symfony\Component\HttpFoundation\RequestStack;
23
use Vich\UploaderBundle\Storage\FlysystemStorage;
24
25
final class MessageProcessor implements ProcessorInterface
26
{
27
    public function __construct(
28
        private readonly ProcessorInterface $persistProcessor,
29
        private readonly ProcessorInterface $removeProcessor,
30
        private readonly FlysystemStorage $storage,
31
        private readonly EntityManagerInterface $entityManager,
32
        private readonly ResourceNodeRepository $resourceNodeRepository,
33
        private readonly Security $security,
34
        private readonly RequestStack $requestStack
35
    ) {}
36
37
    public function process($data, Operation $operation, array $uriVariables = [], array $context = [])
38
    {
39
        if ($operation instanceof DeleteOperationInterface) {
40
            return $this->removeProcessor->process($data, $operation, $uriVariables, $context);
41
        }
42
43
        if ($operation instanceof Patch && str_contains($operation->getUriTemplate(), 'delete-for-user')) {
44
            return $this->processDeleteForUser($data);
45
        }
46
47
        /** @var Message $message */
48
        $message = $this->persistProcessor->process($data, $operation, $uriVariables, $context);
49
50
        foreach ($message->getAttachments() as $attachment) {
51
            $attachment->resourceNode->addResourceFile(
52
                $attachment->getResourceFileToAttach()
53
            );
54
55
            foreach ($message->getReceivers() as $receiver) {
56
                $attachment->addUserLink($receiver->getReceiver());
57
            }
58
        }
59
60
        $user = $this->security->getUser();
61
        if (!$user) {
62
            throw new LogicException('User not found.');
63
        }
64
65
        // Check if the relationship already exists
66
        $messageRelUserRepository = $this->entityManager->getRepository(MessageRelUser::class);
67
        $existingRelation = $messageRelUserRepository->findOneBy([
68
            'message' => $message,
69
            'receiver' => $user,
70
            'receiverType' => MessageRelUser::TYPE_SENDER,
71
        ]);
72
73
        if (!$existingRelation) {
74
            $messageRelUser = new MessageRelUser();
75
            $messageRelUser->setMessage($message);
76
            $messageRelUser->setReceiver($user);
77
            $messageRelUser->setReceiverType(MessageRelUser::TYPE_SENDER);
78
            $this->entityManager->persist($messageRelUser);
79
        }
80
81
        if (Message::MESSAGE_TYPE_INBOX === $message->getMsgType()) {
82
            $this->saveNotificationForInboxMessage($message);
83
        }
84
85
        $this->entityManager->flush();
86
87
        return $message;
88
    }
89
90
    private function processDeleteForUser($data): Message
91
    {
92
        /** @var Message $message */
93
        $message = $data;
94
95
        $request = $this->requestStack->getCurrentRequest();
96
        if (!$request) {
97
            throw new LogicException('Cannot get current request');
98
        }
99
100
        $requestData = json_decode($request->getContent(), true);
101
        if (!isset($requestData['userId'])) {
102
            throw new InvalidArgumentException('The field userId is required.');
103
        }
104
105
        $userId = $requestData['userId'];
106
        $messageRelUserRepository = $this->entityManager->getRepository(MessageRelUser::class);
107
        $messageRelUser = $messageRelUserRepository->findOneBy([
108
            'message' => $message,
109
            'receiver' => $userId,
110
        ]);
111
112
        if ($messageRelUser) {
113
            $this->entityManager->remove($messageRelUser);
114
            $this->entityManager->flush();
115
        }
116
117
        return $message;
118
    }
119
120
    private function saveNotificationForInboxMessage(Message $message): void
121
    {
122
        $sender_info = api_get_user_info(
123
            $message->getSender()->getId()
124
        );
125
126
        $userIdList = $message
127
            ->getReceivers()
128
            ->map(fn (MessageRelUser $messageRelUser): int => $messageRelUser->getReceiver()->getId())
129
            ->getValues()
130
        ;
131
132
        $attachmentList = [];
133
134
        /** @var MessageAttachment $messageAttachment */
135
        foreach ($message->getAttachments() as $messageAttachment) {
136
            $stream = $this->resourceNodeRepository->getResourceNodeFileStream(
137
                $messageAttachment->resourceNode
138
            );
139
140
            $attachmentList[] = [
141
                'stream' => $stream,
142
                'filename' => $messageAttachment->getFilename(),
143
            ];
144
        }
145
146
        (new Notification())
147
            ->saveNotification(
148
                $message->getId(),
149
                Notification::NOTIFICATION_TYPE_MESSAGE,
150
                $userIdList,
151
                $message->getTitle(),
152
                $message->getContent(),
153
                $sender_info,
154
                $attachmentList,
155
            )
156
        ;
157
    }
158
}
159