Passed
Push — master ( ab70cb...f24687 )
by Alexey
12:08
created

InitController::buildArrayChild()   B

Complexity

Conditions 7
Paths 3

Size

Total Lines 22
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
c 0
b 0
f 0
dl 0
loc 22
rs 8.8333
cc 7
nc 3
nop 1
1
<?php
2
3
namespace modules\rbac\console;
4
5
use Yii;
6
use yii\helpers\ArrayHelper;
7
use yii\console\Controller;
8
use modules\rbac\components\AuthorRule;
9
use console\components\helpers\Console;
10
use modules\rbac\models\Role;
11
use modules\rbac\models\Permission;
12
use modules\rbac\Module;
13
use Exception;
14
15
/**
16
 * Class RbacController
17
 * Инициализатор RBAC выполняется в консоли php yii rbac/init
18
 *
19
 * @package console\controllers
20
 *
21
 * @property-read array $permissions
22
 * @property-read array $roles
23
 */
24
class InitController extends Controller
25
{
26
    const TYPE_ROLE = 'Roles';
27
    const TYPE_PERMISSION = 'Permissions';
28
29
    /**
30
     * Color
31
     * @var bool
32
     */
33
    public $color = true;
34
35
    /**
36
     * Initialize RBAC
37
     */
38
    public function actionIndex()
39
    {
40
        if ($this->processInit()) {
41
            $this->stdout(
42
                Console::convertEncoding(Module::translate('module', 'Success!')),
43
                Console::FG_GREEN,
44
                Console::BOLD
45
            );
46
            $this->stdout(PHP_EOL);
47
        } else {
48
            $this->stderr(
49
                Console::convertEncoding(Module::translate('module', 'Fail!')),
50
                Console::FG_RED,
51
                Console::BOLD
52
            );
53
        }
54
    }
55
56
    /**
57
     * @return bool
58
     * @throws Exception
59
     */
60
    public function processInit()
61
    {
62
        $auth = Yii::$app->authManager;
63
        $this->processClear($auth);
64
        $roles = $this->processCreate($auth, $this->getRoles());
65
        $permissions = $this->processCreate($auth, $this->getPermissions(), self::TYPE_PERMISSION);
66
        $this->processAddPermissionToRoles($auth, $roles, $permissions);
67
68
        //$this->processAddChildRoles($auth, $roles); //Inheritance of roles - If you uncomment, the roles are inherited
69
70
        // Assign a super administrator role to the user from id 1
71
        $role = ArrayHelper::getValue($roles, Role::ROLE_SUPER_ADMIN);
72
        return $this->processAssignUserToRole($auth, $role);
73
    }
74
75
    /**
76
     * Clear
77
     *
78
     * @param $auth yii\rbac\ManagerInterface
79
     * @return bool
80
     */
81
    protected function processClear($auth)
82
    {
83
        $auth->removeAll();
84
        return true;
85
    }
86
87
    /**
88
     * Create Roles and Permissions
89
     *
90
     * @param object $auth
91
     * @param array $array
92
     * @param string $type
93
     * @return array
94
     */
95
    protected function processCreate($auth, $array = [], $type = self::TYPE_ROLE)
96
    {
97
        $result = [];
98
        foreach ($array as $key => $value) {
99
            $result[$key] = ($type === self::TYPE_ROLE) ? $auth->createRole($key) : $auth->createPermission($key);
100
            $result[$key]->description = Module::translate('module', $value);
101
            // Add rules
102
            if ($key === Permission::PERMISSION_UPDATE_OWN_POST) {
103
                $authorRule = new AuthorRule;
104
                $auth->add($authorRule);
105
                $result[$key]->ruleName = $authorRule->name;
106
            }
107
            $auth->add($result[$key]);
108
        }
109
        return $result;
110
    }
111
112
    /**
113
     * Add Permissions for Roles
114
     *
115
     * @param object $auth
116
     * @param array $roles
117
     * @param array $permissions
118
     * @throws Exception
119
     */
120
    protected function processAddPermissionToRoles($auth, $roles = [], $permissions = [])
121
    {
122
        foreach (Permission::getGroups() as $role => $group) {
123
            foreach ($group as $permission) {
124
                $auth->addChild(
125
                    ArrayHelper::getValue($roles, $role),
126
                    ArrayHelper::getValue($permissions, $permission)
127
                );
128
            }
129
        }
130
    }
131
132
    /**
133
     * Add Child role for Roles
134
     *
135
     * @param object $auth
136
     * @param array $roles
137
     * @throws Exception
138
     */
139
    protected function processAddChildRoles($auth, $roles = [])
140
    {
141
        $arrayChild = $this->buildArrayChild(Role::tree());
142
        foreach ($arrayChild as $item) {
143
            foreach ($item as $role => $child) {
144
                $auth->addChild(
145
                    ArrayHelper::getValue($roles, $role),
146
                    ArrayHelper::getValue($roles, $child)
147
                );
148
            }
149
        }
150
    }
151
152
    /**
153
     * @param array $array
154
     * @return array
155
     */
156
    protected function buildArrayChild($array)
157
    {
158
        $result = [];
159
        foreach ($array as $key => $item) {
160
            if (is_array($item)) {
161
                foreach ($item as $k => $v) {
162
                    if (is_string($k)) {
163
                        $result[][$key] = $k;
164
                    }
165
                    if (is_string($v)) {
166
                        $result[][$key] = $v;
167
                    }
168
                    if (is_array($v)) {
169
                        $child = $this->buildArrayChild([$k => $item[$k]]);
170
                        $result = array_merge($result, $child);
171
                    }
172
                }
173
            } else {
174
                $result[] = $item;
175
            }
176
        }
177
        return $result;
178
    }
179
180
    /**
181
     * Assign Role to User
182
     * @param object $auth
183
     * @param $role
184
     * @param integer $userId
185
     * @return bool
186
     */
187
    protected function processAssignUserToRole($auth, $role, $userId = 1)
188
    {
189
        $auth->assign($role, $userId);
190
        return true;
191
    }
192
193
    /**
194
     * Roles
195
     *
196
     * @return array
197
     */
198
    protected function getRoles()
199
    {
200
        $role = new Role();
201
        return $role->getRolesArray();
202
    }
203
204
    /**
205
     * Permissions
206
     *
207
     * @return array
208
     */
209
    protected function getPermissions()
210
    {
211
        $permission = new Permission();
212
        return $permission->getPermissionsArray();
213
    }
214
}
215