Failed Conditions
Pull Request — master (#142)
by Zac
04:15
created

TestGroupVoter::supportsClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Overwatch\TestBundle\Security;
4
5
use Overwatch\UserBundle\Entity\User;
6
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
7
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
8
use Symfony\Component\Security\Core\Role\Role;
9
10
/**
11
 * TestGroupVoter
12
 */
13
class TestGroupVoter implements VoterInterface
14
{
15
    const VIEW = 'view';
16
    const EDIT = 'edit';
17
    
18
    public function supportsAttribute($attribute)
19
    {
20
        return in_array($attribute, [
21
            self::VIEW,
22
            self::EDIT,
23
        ]);
24
    }
25
    
26 5
    public function supportsClass($class)
27
    {
28 5
        $supportedClass = 'Overwatch\TestBundle\Entity\TestGroup';
29 5
        return $supportedClass === $class || is_subclass_of($class, $supportedClass);
30
    }
31
    
32 5
    public function vote(TokenInterface $token, $group, array $attributes)
33
    {
34
        // check if class of this object is supported by this voter
35 5
        if (!$this->supportsClass(get_class($group))) {
36 5
            return VoterInterface::ACCESS_ABSTAIN;
37
        }
38
39
        // check if the given attribute is covered by this voter
40
        if (!$this->supportsAttribute($attributes[0])) {
41
            return VoterInterface::ACCESS_ABSTAIN;
42
        }
43
44
        // get current logged in user
45
        $user = $token->getUser();
46
        
47
        //allow the token to have ROLE_SUPER_ADMIN before we check the user, for testing
48
        if (in_array(new Role('ROLE_SUPER_ADMIN'), $token->getRoles())) {
49
            return VoterInterface::ACCESS_GRANTED;
50
        }
51
        
52
        // make sure there is a user object (i.e. that the user is logged in)
53
        if (!$user instanceof User) {
54
            return VoterInterface::ACCESS_DENIED;
55
        }
56
57
        switch ($attributes[0]) {
58
            case self::VIEW:
59
                if ($user->hasGroup($group->getName())) {
60
                    return VoterInterface::ACCESS_GRANTED;
61
                }
62
                break;
63
64
            case self::EDIT:
65
                if ($user->hasGroup($group->getName()) && $user->hasRole('ROLE_ADMIN')) {
66
                    return VoterInterface::ACCESS_GRANTED;
67
                }
68
                break;
69
        }
70
71
        return VoterInterface::ACCESS_DENIED;
72
    }
73
}
74