Completed
Push — master ( 14c4d1...ccef5b )
by Alexey
03:02
created

Role::processCheckRoleName()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
cc 3
eloc 5
nc 3
nop 1
1
<?php
2
3
namespace modules\rbac\models;
4
5
use Yii;
6
use yii\base\Model;
7
use modules\rbac\traits\ModuleTrait;
8
use modules\rbac\Module;
9
10
/**
11
 * Class Role
12
 * @package modules\rbac\models
13
 */
14
class Role extends Model
15
{
16
    use ModuleTrait;
17
18
    // константы ролей
19
    const ROLE_SUPER_ADMIN = 'super_admin';
20
    const ROLE_SUPER_ADMIN_DESCRIPTION = 'Super Administrator';
21
22
    const ROLE_ADMIN = 'admin';
23
    const ROLE_ADMIN_DESCRIPTION = 'Administrator';
24
25
    const ROLE_MANAGER = 'manager';
26
    const ROLE_MANAGER_DESCRIPTION = 'Manager';
27
28
    const ROLE_EDITOR = 'editor';
29
    const ROLE_EDITOR_DESCRIPTION = 'Editor';
30
31
    const ROLE_DEFAULT = 'user';
32
    const ROLE_DEFAULT_DESCRIPTION = 'User';
33
34
    // сценарии
35
    const SCENARIO_CREATE = 'create';
36
    const SCENARIO_UPDATE = 'update';
37
38
    public $name;
39
    public $description;
40
    public $isNewRecord = false;
41
42
    /** @var  array $rolesByRole Наследуемые роли */
43
    public $rolesByRole;
44
    /** @var  array $itemsRoles Доступные роли */
45
    public $itemsRoles;
46
47
    /** @var  array $permissionsByRole Установленные разрешения для роли */
48
    public $permissionsByRole;
49
    /** @var array $itemsPermissions Разрешения */
50
    public $itemsPermissions;
51
52
    /**
53
     * @inheritdoc
54
     * @return array
55
     */
56
    public function rules()
57
    {
58
        return [
59
            ['name', 'required', 'on' => self::SCENARIO_CREATE],
60
            ['name', 'string', 'max' => 64, 'on' => self::SCENARIO_CREATE],
61
            ['name', 'match', 'pattern' => '#^[\w_-]+$#i', 'message' => Module::t('module', 'It is allowed to use the Latin alphabet, numbers, dashes and underscores.(A-z,0-1,-,_)'), 'on' => self::SCENARIO_CREATE],
62
            ['name', 'validateUniqueName', 'skipOnEmpty' => false, 'skipOnError' => false, 'on' => [self::SCENARIO_CREATE]],
63
64
            [['description'], 'string'],
65
            [['rolesByRole', 'itemsRoles', 'permissionsByRole', 'itemsPermissions'], 'required', 'message' => Module::t('module', 'You must select in the field «{attribute}».'), 'on' => self::SCENARIO_UPDATE],
66
        ];
67
    }
68
69
    /**
70
     * @param string $attribute
71
     */
72
    public function validateUniqueName($attribute)
73
    {
74
        if (!$attribute) {
75
            $this->addError($attribute, Module::t('module', 'Enter name role.'));
76
        }
77
        if (!$this->hasErrors()) {
78
            $this->processCheckRoleName($attribute);
79
        }
80
    }
81
82
    /**
83
     * @param string $attribute
84
     * @return mixed
85
     */
86
    public function processCheckRoleName($attribute)
87
    {
88
        if (!empty($this->name)) {
89
            $auth = Yii::$app->authManager;
90
            if ($auth->getRole($this->name)) {
91
                $this->addError($attribute, Module::t('module', 'This name is already taken.'));
92
            }
93
        }
94
        return $attribute;
95
    }
96
97
    /**
98
     * @return array
99
     */
100
    public function scenarios()
101
    {
102
        $scenarios = parent::scenarios();
103
        $scenarios[self::SCENARIO_CREATE] = ['name', 'description'];
104
        $scenarios[self::SCENARIO_UPDATE] = ['name', 'description', 'rolesByRole', 'itemsRoles', 'permissionsByRole', 'itemsPermissions'];
105
        return $scenarios;
106
    }
107
108
    /**
109
     * @inheritdoc
110
     * @return array
111
     */
112
    public function attributeLabels()
113
    {
114
        return [
115
            'name' => Module::t('module', 'Name'),
116
            'description' => Module::t('module', 'Description'),
117
            'rolesByRole' => Module::t('module', 'Roles by role'),
118
            'itemsRoles' => Module::t('module', 'Items roles'),
119
            'permissionsByRole' => Module::t('module', 'Permissions by role'),
120
            'itemsPermissions' => Module::t('module', 'Items permissions'),
121
        ];
122
    }
123
124
    /**
125
     * Возвращает установленные разрешения для роли
126
     * @return array
127
     */
128
    public function getPermissionsByRole()
129
    {
130
        $auth = Yii::$app->authManager;
131
        $perm = $auth->getPermissionsByRole($this->name);
132
        $arr = [];
133
        foreach ($perm as $value) {
134
            if ($value->name != $this->name) {
135
                $arr[$value->name] = $value->name . ' (' . $value->description . ')';
136
            }
137
        }
138
        return $arr;
139
    }
140
141
    /**
142
     * Возвращает все разрешения
143
     * @return array
144
     */
145
    public function getItemsPermissions()
146
    {
147
        $auth = Yii::$app->authManager;
148
        $perm = $auth->getPermissions();
149
        $arr = [];
150
        foreach ($perm as $value) {
151
            if ($value->name != $this->name) {
152
                $arr[$value->name] = $value->name . ' (' . $value->description . ')';
153
            }
154
        }
155
        $permByRole = $this->getPermissionsByRole();
156
        return array_diff($arr, $permByRole);
157
    }
158
159
    /**
160
     * Возвращает дочерние роли
161
     * @return array
162
     */
163
    public function getRolesByRole()
164
    {
165
        $auth = Yii::$app->authManager;
166
        $roles = $auth->getChildRoles($this->name);
167
        $arr = [];
168
        foreach ($roles as $value) {
169
            if ($value->name != $this->name) {
170
                $arr[$value->name] = $value->name . ' (' . $value->description . ')';
171
            }
172
        }
173
        return $arr;
174
    }
175
176
    /**
177
     * Возвращает все роли
178
     * @return array
179
     */
180
    public function getItemsRoles()
181
    {
182
        $auth = Yii::$app->authManager;
183
        $roles = $auth->getRoles();
184
        $arr = [];
185
        foreach ($roles as $value) {
186
            if ($value->name != $this->name) {
187
                $arr[$value->name] = $value->name . ' (' . $value->description . ')';
188
            }
189
        }
190
        $rolesByRole = $this->getRolesByRole();
191
        return array_diff($arr, $rolesByRole);
192
    }
193
194
    /**
195
     * @return \yii\rbac\Role[]
196
     */
197
    public function getRoleChild()
198
    {
199
        $auth = Yii::$app->authManager;
200
        return $auth->getChildRoles($this->name);
201
    }
202
203
    /**
204
     * Возвращает массив дочерних ролей
205
     * @return array
206
     */
207
    public function getRoleChildArray()
208
    {
209
        $roles = $this->getRoleChild();
210
        $arr = [];
211
        foreach ($roles as $value) {
212
            if ($value->name != $this->name) {
213
                $arr[$value->name] = $value->description;
214
            }
215
        }
216
        return $arr;
217
    }
218
219
    /**
220
     * Получаем все роли
221
     * @return \yii\rbac\Role[]
222
     */
223
    public function getRoles()
224
    {
225
        $auth = Yii::$app->authManager;
226
        return $auth->getRoles();
227
    }
228
229
    /**
230
     * Возвращает массив ролей
231
     * @return array
232
     */
233
    public function getRoleItemsArray()
234
    {
235
        $roles = $this->getRoles();
236
        $arr = [];
237
        foreach ($roles as $value) {
238
            if ($value->name != $this->name) {
239
                $arr[$value->name] = $value->description;
240
            }
241
        }
242
        return $arr;
243
    }
244
245
    /**
246
     *
247
     * @return array
248
     */
249
    public function getRolePermissions()
250
    {
251
        $auth = Yii::$app->authManager;
252
        $children = $auth->getChildren($this->name);
253
        $perm = [];
254
        foreach ($children as $key => $child) {
255
            if ($child->type == 2)
256
                $perm[$key] = $child;
257
        }
258
        return $perm;
259
    }
260
261
    /**
262
     * Все дети
263
     * @return \yii\rbac\Item[]
264
     */
265
    public function getChildren()
266
    {
267
        $auth = Yii::$app->authManager;
268
        return $auth->getChildren($this->name);
269
    }
270
}
271