RoleChecker   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 21
dl 0
loc 47
c 1
b 0
f 0
wmc 10
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
B __invoke() 0 35 9
1
<?php
2
3
declare(strict_types=1);
4
5
namespace DH\AuditorBundle\Security;
6
7
use DH\Auditor\Provider\Doctrine\Configuration;
8
use DH\Auditor\Provider\Doctrine\DoctrineProvider;
9
use DH\Auditor\Security\RoleCheckerInterface;
10
use DH\Auditor\User\UserInterface;
11
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
12
13
class RoleChecker implements RoleCheckerInterface
14
{
15
    private AuthorizationCheckerInterface $authorizationChecker;
16
17
    private DoctrineProvider $provider;
18
19
    public function __construct(AuthorizationCheckerInterface $authorizationChecker, DoctrineProvider $doctrineProvider)
20
    {
21
        $this->authorizationChecker = $authorizationChecker;
22
        $this->provider = $doctrineProvider;
23
    }
24
25
    public function __invoke(string $entity, string $scope): bool
26
    {
27
        $userProvider = $this->provider->getAuditor()->getConfiguration()->getUserProvider();
28
        $user = null !== $userProvider ? $userProvider() : null;
29
        $authorizationChecker = null !== $userProvider ? $this->authorizationChecker : null;
30
31
        if (!($user instanceof UserInterface) || !($authorizationChecker instanceof AuthorizationCheckerInterface)) {
32
            // If no security defined or no user identified, consider access granted
33
            return true;
34
        }
35
36
        \assert($this->provider->getConfiguration() instanceof Configuration);
37
        $entities = $this->provider->getConfiguration()->getEntities();
38
        $roles = $entities[$entity]['roles'] ?? null;
39
40
        if (null === $roles) {
41
            // If no roles are configured, consider access granted
42
            return true;
43
        }
44
45
        if (!\array_key_exists($scope, $roles)) {
46
            // If no roles for the given scope are configured, consider access granted
47
            return true;
48
        }
49
50
        // roles are defined for the give scope
51
        foreach ($roles[$scope] as $role) {
52
            if ($authorizationChecker->isGranted($role)) {
53
                // role granted => access granted
54
                return true;
55
            }
56
        }
57
58
        // access denied
59
        return false;
60
    }
61
}
62