UpdateUserVoter::voteOnAttribute()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 22
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 10.3999

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 22
ccs 4
cts 10
cp 0.4
rs 9.6111
c 0
b 0
f 0
cc 5
nc 7
nop 3
crap 10.3999
1
<?php
2
3
/*
4
 * (c) Lukasz D. Tulikowski <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace App\Security\Voter\User;
13
14
use App\Entity\User;
15
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
16
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
17
18
class UpdateUserVoter extends Voter
19
{
20
    public const CAN_UPDATE_USER = 'CAN_UPDATE_USER';
21
22
    /**
23
     * {@inheritdoc}
24
     */
25 13
    protected function supports($attribute, $subject)
26
    {
27
        // you only want to vote if the attribute and subject are what you expect
28 13
        return self::CAN_UPDATE_USER === $attribute && ($subject instanceof User || null === $subject);
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34 2
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
35
    {
36
        // our previous business logic indicates that mods and admins can do it regardless
37 2
        foreach ($token->getRoles() as $role) {
38 2
            if (\in_array($role->getRole(), ['ROLE_MODERATOR', 'ROLE_ADMIN'])) {
39 2
                return true;
40
            }
41
        }
42
43
        // allow controller handle not found subject
44
        if (null === $subject) {
45
            return true;
46
        }
47
48
        $user = $token->getUser();
49
50
        // allow user to update account
51
        if ($user instanceof User) {
52
            return $subject->getId() === $user->getId();
53
        }
54
55
        return false;
56
    }
57
}
58