Passed
Pull Request — master (#5329)
by Angel Fernando Quiroz
09:42
created

CCalendarEventStateProcessor   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 18
dl 0
loc 53
rs 10
c 0
b 0
f 0
wmc 8

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isPersonalEvent() 0 15 4
A process() 0 23 3
A __construct() 0 5 1
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\Operation;
10
use ApiPlatform\State\ProcessorInterface;
11
use Chamilo\CoreBundle\Entity\AgendaReminder;
12
use Chamilo\CoreBundle\Entity\User;
13
use Chamilo\CoreBundle\Settings\SettingsManager;
14
use Chamilo\CourseBundle\Entity\CCalendarEvent;
15
use Exception;
16
use Symfony\Bundle\SecurityBundle\Security;
17
18
/**
19
 * @implements ProcessorInterface<CCalendarEvent>
20
 */
21
final class CCalendarEventStateProcessor implements ProcessorInterface
22
{
23
    public function __construct(
24
        private readonly ProcessorInterface $persistProcessor,
25
        private readonly Security $security,
26
        private readonly SettingsManager $settingsManager,
27
    ) {}
28
29
    /**
30
     * @param mixed $data
31
     *
32
     * @throws Exception
33
     */
34
    public function process($data, Operation $operation, array $uriVariables = [], array $context = []): CCalendarEvent
35
    {
36
        \assert($data instanceof CCalendarEvent);
37
38
        /** @var User $currentUser */
39
        $currentUser = $this->security->getUser();
40
41
        $data->setCreator($currentUser);
42
43
        if ($this->isPersonalEvent($data)) {
44
            if ($currentUser->getResourceNode()->getId() !== $data->getParentResourceNode()) {
45
                throw new Exception('Not allowed');
46
            }
47
        }
48
49
        $data->getReminders()->forAll(function (int $i, AgendaReminder $reminder) {
50
            $reminder->setType('');
51
52
            return $reminder->decodeDateInterval();
53
        });
54
55
        /** @var CCalendarEvent $result */
56
        return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
57
    }
58
59
    private function isPersonalEvent(CCalendarEvent $event): bool
60
    {
61
        $type = 'personal';
62
63
        if (!empty($event->getResourceLinkArray())) {
64
            foreach ($event->getResourceLinkArray() as $link) {
65
                if (isset($link['cid'])) {
66
                    $type = 'course';
67
68
                    break;
69
                }
70
            }
71
        }
72
73
        return 'personal' === $type;
74
    }
75
}
76