Passed
Push — dependabot/npm_and_yarn/microm... ( e84ba6...f2f212 )
by
unknown
10:03
created

MessageRelUserVoter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
dl 0
loc 37
rs 10
c 1
b 0
f 0
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A supports() 0 4 2
A voteOnAttribute() 0 21 3
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
declare(strict_types=1);
6
7
namespace Chamilo\CoreBundle\Security\Authorization\Voter;
8
9
use Chamilo\CoreBundle\Entity\MessageRelUser;
10
use Chamilo\CoreBundle\Entity\User;
11
use Symfony\Bundle\SecurityBundle\Security;
12
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
13
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
14
use Symfony\Component\Security\Core\User\UserInterface;
15
16
class MessageRelUserVoter extends Voter
17
{
18
    public const DELETE = 'DELETE';
19
    public const VIEW = 'VIEW';
20
    public const EDIT = 'EDIT';
21
22
    public function __construct(
23
        private readonly Security $security
24
    ) {}
25
26
    protected function supports(string $attribute, mixed $subject): bool
27
    {
28
        return \in_array($attribute, [self::DELETE, self::VIEW, self::EDIT])
29
            && $subject instanceof MessageRelUser;
30
    }
31
32
    protected function voteOnAttribute(string $attribute, mixed $subject, TokenInterface $token): bool
33
    {
34
        $user = $token->getUser();
35
36
        if (!$user instanceof UserInterface) {
37
            return false;
38
        }
39
40
        if ($this->security->isGranted('ROLE_ADMIN')) {
41
            return true;
42
        }
43
44
        \assert($user instanceof User);
45
        \assert($subject instanceof MessageRelUser);
46
47
        $message = $subject->getMessage();
48
        $isReceiver = $message->hasUserReceiver($user);
49
50
        return match ($attribute) {
51
            self::VIEW, self::EDIT, self::DELETE => $isReceiver,
52
            default => false,
53
        };
54
    }
55
}
56