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

RoleHierarchyResolver::resolveRoleHierarchy()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 18
rs 9.2
cc 4
eloc 10
nc 4
nop 2
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