RoleHierarchy::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 1
1
<?php
2
3
/*
4
 * The MIT License (MIT)
5
 *
6
 * Copyright (c) 2014-2016 Spomky-Labs
7
 *
8
 * This software may be modified and distributed under the terms
9
 * of the MIT license.  See the LICENSE file for details.
10
 */
11
12
namespace SpomkyLabs\RoleHierarchyBundle\Security;
13
14
use SpomkyLabs\RoleHierarchyBundle\Model\RoleInterface;
15
use SpomkyLabs\RoleHierarchyBundle\Model\RoleManagerInterface;
16
use Symfony\Component\Security\Core\Role\RoleHierarchy as BaseRoleHierarchy;
17
18
final class RoleHierarchy extends BaseRoleHierarchy
19
{
20
    /**
21
     * RoleHierarchy constructor.
22
     *
23
     * @param \SpomkyLabs\RoleHierarchyBundle\Model\RoleManagerInterface $role_manager
24
     */
25
    public function __construct(RoleManagerInterface $role_manager)
26
    {
27
        $map = $this->buildRolesTree($role_manager);
28
        parent::__construct($map);
29
    }
30
31
    /**
32
     * @param \SpomkyLabs\RoleHierarchyBundle\Model\RoleManagerInterface $role_manager
33
     *
34
     * @return array
35
     */
36
    protected function buildRolesTree(RoleManagerInterface $role_manager)
37
    {
38
        $hierarchy = [];
39
        $roles = $role_manager->getRoles();
40
        foreach ($roles as $role) {
41
            if ($role instanceof RoleInterface) {
42
                if ($role->getParent()) {
43
                    if (!isset($hierarchy[$role->getParent()->getName()])) {
44
                        $hierarchy[$role->getParent()->getName()] = [];
45
                    }
46
                    $hierarchy[$role->getParent()->getName()][] = $role->getName();
47
                } else {
48
                    if (!isset($hierarchy[$role->getName()])) {
49
                        $hierarchy[$role->getName()] = [];
50
                    }
51
                }
52
            }
53
        }
54
55
        return $hierarchy;
56
    }
57
}
58