Completed
Push — master ( 2dd394...56f862 )
by Dominik
02:16
created

RoleHierarchyResolver   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 6
c 0
b 0
f 0
lcom 1
cbo 0
dl 0
loc 50
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A resolve() 0 4 1
A resolveRoleHierarchy() 0 18 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Chubbyphp\Security\Authorization;
6
7
final class RoleHierarchyResolver implements RoleHierarchyResolverInterface
8
{
9
    /**
10
     * @var array
11
     */
12
    private $roleHierarchy;
13
14
    /**
15
     * @param array $roleHierarchy
16
     */
17
    public function __construct(array $roleHierarchy = [])
18
    {
19
        $this->roleHierarchy = $roleHierarchy;
20
    }
21
22
    /**
23
     * @param array $roles
24
     *
25
     * @return array
26
     */
27
    public function resolve(array $roles): array
28
    {
29
        return $this->resolveRoleHierarchy($roles);
30
    }
31
32
    /**
33
     * @param array $roles
34
     * @param array $alreadySolvedRoles
35
     *
36
     * @return array
37
     */
38
    private function resolveRoleHierarchy(array $roles, array $alreadySolvedRoles = []): array
39
    {
40
        foreach ($roles as $role) {
41
            if (isset($this->roleHierarchy[$role])) {
42
                if (in_array($role, $alreadySolvedRoles, true)) {
43
                    continue;
44
                }
45
46
                $alreadySolvedRoles[] = $role;
47
                $resolveRoles = $this->resolveRoleHierarchy($this->roleHierarchy[$role], $alreadySolvedRoles);
48
                $roles = array_merge($roles, $resolveRoles);
49
            }
50
        }
51
52
        sort($roles);
53
54
        return array_unique($roles);
55
    }
56
}
57