DeleteReviewVoter::voteOnAttribute()   A
last analyzed

Complexity

Conditions 5
Paths 7

Size

Total Lines 22
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.2

Importance

Changes 0
Metric Value
eloc 9
dl 0
loc 22
ccs 8
cts 10
cp 0.8
rs 9.6111
c 0
b 0
f 0
cc 5
nc 7
nop 3
crap 5.2
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\Review;
13
14
use App\Entity\Review;
15
use App\Entity\User;
16
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
17
use Symfony\Component\Security\Core\Authorization\Voter\Voter;
18
19
class DeleteReviewVoter extends Voter
20
{
21
    public const CAN_DELETE_REVIEW = 'CAN_DELETE_REVIEW';
22
23
    /**
24
     * {@inheritdoc}
25
     */
26 19
    protected function supports($attribute, $subject)
27
    {
28
        // you only want to vote if the attribute and subject are what you expect
29 19
        return self::CAN_DELETE_REVIEW === $attribute && ($subject instanceof Review || null === $subject);
30
    }
31
32
    /**
33
     * {@inheritdoc}
34
     */
35 3
    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
36
    {
37
        // our previous business logic indicates that admins can do it regardless
38 3
        foreach ($token->getRoles() as $role) {
39 2
            if (\in_array($role->getRole(), ['ROLE_ADMIN'])) {
40 2
                return true;
41
            }
42
        }
43
44
        // allow controller handle not found subject
45 1
        if (null === $subject) {
46
            return true;
47
        }
48
49 1
        $user = $token->getUser();
50
51
        // allow user to delete account
52 1
        if ($user instanceof User) {
53
            return $subject->getAuthor()->getId() === $user->getId();
54
        }
55
56 1
        return false;
57
    }
58
}
59