Completed
Push — master ( 4e378a...cfdcd7 )
by Yann
05:10
created

HasRoles   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Dependencies 3

Importance

Changes 0
Metric Value
wmc 4
cbo 3
dl 0
loc 55
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A __invoke() 0 23 3
1
<?php
2
3
namespace Yokai\SecurityExtraBundle\Callback;
4
5
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
6
use Symfony\Component\Security\Core\Role\Role;
7
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
8
9
/**
10
 * @author Yann Eugoné <[email protected]>
11
 */
12
class HasRoles
13
{
14
    /**
15
     * The role hierarchy.
16
     * @var RoleHierarchyInterface
17
     */
18
    private $roleHierarchy;
19
20
    /**
21
     * The roles that must be accessible.
22
     * @var string[]
23
     */
24
    private $roles;
25
26
    /**
27
     * @param RoleHierarchyInterface $roleHierarchy The role hierarchy
28
     * @param string[]               $roles         The roles that must be accessible
29
     */
30
    public function __construct(RoleHierarchyInterface $roleHierarchy, $roles)
31
    {
32
        $this->roleHierarchy = $roleHierarchy;
33
        $this->roles = $roles;
34
    }
35
36
    /**
37
     * Check if the provided token has access to every configured roles.
38
     *
39
     * @param TokenInterface $token The security token
40
     *
41
     * @return bool Whether or not token has all configured roles
42
     */
43
    public function __invoke(TokenInterface $token)
44
    {
45
        // extract and normalize roles from hierarchy
46
        $roles = array_map(
47
            function (Role $role) {
48
                return $role->getRole();
49
            },
50
            $this->roleHierarchy->getReachableRoles($token->getRoles())
51
        );
52
53
        // iterating over all configured roles
54
        // if a single role is missing this will return false
55
        foreach ($this->roles as $role) {
56
            if (!in_array($role, $roles, true)) {
57
                return false;
58
            }
59
        }
60
61
        // all configured roles are accessible to the security token
62
        // return true
63
64
        return true;
65
    }
66
}
67