Completed
Push — master ( 5b873e...d824de )
by Alexey
02:27
created

RolesController::actionAssign()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 22
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
c 0
b 0
f 0
rs 9.2
cc 3
eloc 17
nc 4
nop 0
1
<?php
2
3
namespace modules\rbac\console;
4
5
use Yii;
6
use yii\console\Controller;
7
use yii\console\Exception;
8
use yii\helpers\ArrayHelper;
9
use modules\users\models\User;
10
use console\components\helpers\Console;
0 ignored issues
show
Bug introduced by
The type console\components\helpers\Console was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
11
12
/**
13
 * Class RolesController
14
 * @package modules\rbac\console
15
 */
16
class RolesController extends Controller
17
{
18
    /**
19
     * Adds role to user
20
     * @throws Exception
21
     * @throws \Exception
22
     */
23
    public function actionAssign()
24
    {
25
        $authManager = Yii::$app->authManager;
26
        $username = $this->prompt(Console::convertEncoding(Yii::t('app', 'Username:')), ['required' => true]);
27
        $user = $this->findModel($username);
28
29
        $roles = Yii::$app->authManager->getRoles();
30
        $array = ArrayHelper::map($roles, 'name', 'description');
31
        $encodingArray = Console::convertEncoding($array);
32
        $select = is_array($encodingArray) ? $encodingArray : $array;
33
        $roleName = $this->select(Console::convertEncoding(Yii::t('app', 'Role:')), $select);
34
        $role = $authManager->getRole($roleName);
35
36
        // Проверяем есть ли уже такая роль у пользователя
37
        $userRoles = $this->getUserRoleValue($user->id);
38
        if ($userRoles === null) {
39
            $authManager->assign($role, $user->id);
40
            $this->stdout(Console::convertEncoding(Yii::t('app', 'Success!')), Console::FG_GREEN, Console::BOLD);
41
            $this->stdout(PHP_EOL);
42
        } else {
43
            $this->stdout(Console::convertEncoding(Yii::t('app', 'The user already has a role.')), Console::FG_RED, Console::BOLD);
44
            $this->stdout(PHP_EOL);
45
        }
46
    }
47
48
    /**
49
     * Removes role from user
50
     * @throws Exception
51
     */
52
    public function actionRevoke()
53
    {
54
        $authManager = Yii::$app->authManager;
55
        $username = $this->prompt(Console::convertEncoding(Yii::t('app', 'Username:')), ['required' => true]);
56
        $user = $this->findModel($username);
57
        $roleName = $this->select(
58
            Console::convertEncoding(Yii::t('app', 'Role:')), ArrayHelper::merge(
59
            ['all' => Console::convertEncoding(Yii::t('app', 'All Roles'))],
60
            Console::convertEncoding(
61
                ArrayHelper::map($authManager->getRolesByUser($user->id), 'name', 'description')
62
            )
63
        )
64
        );
65
        if ($roleName == 'all') {
66
            $authManager->revokeAll($user->id);
67
        } else {
68
            $role = $authManager->getRole($roleName);
69
            $authManager->revoke($role, $user->id);
70
        }
71
        $this->stdout(Console::convertEncoding(Yii::t('app', 'Done!')), Console::FG_GREEN, Console::BOLD);
72
        $this->stdout(PHP_EOL);
73
    }
74
75
    /**
76
     * @param string|int $user_id
77
     * @return mixed|null
78
     */
79
    public function getUserRoleValue($user_id)
80
    {
81
        $authManager = Yii::$app->authManager;
82
        if ($role = $authManager->getRolesByUser($user_id)) {
83
            return ArrayHelper::getValue($role, function ($role) {
84
                foreach ($role as $key => $value) {
85
                    return $value->name;
86
                }
87
                return null;
88
            });
89
        }
90
        return null;
91
    }
92
93
    /**
94
     * Finds the User model based on its primary key value.
95
     * If the model is not found, a 404 HTTP exception will be thrown.
96
     *
97
     * @param string $username
98
     * @return null|User the loaded model
99
     * @throws Exception if the model cannot be found
100
     */
101
    private function findModel($username)
102
    {
103
        if (!$model = User::findOne(['username' => $username])) {
104
            throw new Exception(
105
                Console::convertEncoding(
106
                    Yii::t('app', 'User "{:Username}" not found', [':Username' => $username])
107
                )
108
            );
109
        }
110
        return $model;
111
    }
112
}
113