RoleChecker   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 4
dl 0
loc 42
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A hasRole() 0 18 4
1
<?php
2
3
namespace JDecool\Bundle\SecurityRoleCheckerBundle\Security;
4
5
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
6
use Symfony\Component\Security\Core\Role\Role;
7
use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;
8
use Symfony\Component\Security\Core\Role\RoleInterface;
9
use Symfony\Component\Security\Core\User\UserInterface;
10
11
class RoleChecker implements RoleCheckerInterface
12
{
13
    /** @var AuthorizationCheckerInterface */
14
    private $authorizationChecker;
15
16
    /** @var RoleHierarchyInterface */
17
    private $roleHierarchy;
18
19
    /**
20
     * Constructor
21
     *
22
     * @param AuthorizationCheckerInterface $authorizationChecker
23
     * @param RoleHierarchyInterface        $roleHierarchy
24
     */
25
    public function __construct(AuthorizationCheckerInterface $authorizationChecker, RoleHierarchyInterface $roleHierarchy)
26
    {
27
        $this->authorizationChecker = $authorizationChecker;
28
        $this->roleHierarchy        = $roleHierarchy;
29
    }
30
31
    /**
32
     * {@inheritdoc}
33
     */
34
    public function hasRole($role, UserInterface $user = null)
35
    {
36
        if (null === $user) {
37
            return $this->authorizationChecker->isGranted($role);
38
        }
39
40
        $roles = $this->roleHierarchy->getReachableRoles(array_map(function ($role) {
41
            if (is_string($role)) {
42
                return new Role($role);
43
            } elseif (!$role instanceof RoleInterface) {
44
                throw new \InvalidArgumentException(sprintf('$roles must be an array of strings, or RoleInterface instances, but got %s.', gettype($role)));
45
            }
46
47
            return $role;
48
        }, $user->getRoles()));
49
50
        return in_array(new Role($role), $roles);
51
    }
52
}
53