Completed
Pull Request — master (#31)
by
unknown
09:01
created

AbstractIniter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
dl 0
loc 54
ccs 0
cts 18
cp 0
rs 10
c 1
b 0
f 0
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A reinit() 0 4 1
A init() 0 20 5
1
<?php
2
/**
3
 * RBAC implementation for HiPanel
4
 *
5
 * @link      https://github.com/hiqdev/hipanel-rbac
6
 * @package   hipanel-rbac
7
 * @license   BSD-3-Clause
8
 * @copyright Copyright (c) 2016-2020, HiQDev (http://hiqdev.com/)
9
 */
10
11
namespace hipanel\rbac;
12
13
/**
14
 * Initer for AuthManager.
15
 *
16
 * @author Andrii Vasyliev <[email protected]>
17
 */
18
abstract class AbstractIniter implements RbacIniterInterface
19
{
20
    /**
21
     * Provides a tree of permissions to be set in AuthManager.
22
     *
23
     * @return array where:
24
     * - key: role name
25
     * - value: role items
26
     */
27
    abstract public function getTree();
28
29
    /**
30
     * Provides a tree of permissions to be set in AuthManager.
31
     *
32
     * @return array where:
33
     * - key: permission or role name
34
     * - array: role additional data according to `\yii\rbac\Permission` properties
35
     */
36
    abstract public function getMetadata();
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function init(AuthManager $auth)
42
    {
43
        $metadata = $this->getMetadata();
44
45
        foreach (array_keys($this->getTree()) as $roleName) {
46
            $roleMeta = $metadata[$roleName];
47
            $auth->setRole($roleName, $roleMeta['description'] ?? null);
48
        }
49
50
        foreach ($this->getTree() as $roleName => $items) {
51
            foreach ($items as $name) {
52
                $item = $auth->getItem($name);
53
                if ($item === null) {
54
                    $itemMeta = $metadata[$name];
55
                    $item = $auth->setPermission($name, $itemMeta['description'] ?? null);
56
57
                    $itemMeta = $metadata["deny:$name"];
58
                    $auth->setPermission("deny:$name", $itemMeta['description'] ?? null);
59
                }
60
                $auth->setChild($roleName, $item);
61
            }
62
        }
63
    }
64
65
    /**
66
     * {@inheritdoc}
67
     */
68
    public function reinit(AuthManager $auth)
69
    {
70
        $auth->removeAll();
71
        $this->init($auth);
72
    }
73
}
74