Completed
Push — master ( 824c39...b77968 )
by Alexey
02:18
created

RolesController::actionIndex()   A

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 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;
11
12
/**
13
 * Class RolesController
14
 * @package modules\rbac\console
15
 */
16
class RolesController extends Controller
17
{
18
    /**
19
     * @inheritdoc
20
     */
21
    public function actionIndex()
22
    {
23
        echo 'yii rbac/roles/assign - Assign user role.' . PHP_EOL;
24
        echo 'yii rbac/roles/revoke - Revoke user role.' . PHP_EOL;
25
    }
26
27
    /**
28
     * Adds role to user
29
     */
30
    public function actionAssign()
31
    {
32
        $username = $this->prompt(Console::convertEncoding(Yii::t('app', 'Username:')), ['required' => true]);
0 ignored issues
show
Bug introduced by
It seems like \console\components\help...:t('app', 'Username:')) targeting console\components\helpe...sole::convertEncoding() can also be of type array; however, yii\console\Controller::prompt() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
33
        $user = $this->findModel($username);
34
        $roleName = $this->select(Console::convertEncoding(Yii::t('app', 'Role:')), Console::convertEncoding(ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description')));
0 ignored issues
show
Bug introduced by
It seems like \console\components\help...Yii::t('app', 'Role:')) targeting console\components\helpe...sole::convertEncoding() can also be of type array; however, yii\console\Controller::select() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
Bug introduced by
It seems like \console\components\help...'name', 'description')) targeting console\components\helpe...sole::convertEncoding() can also be of type string; however, yii\console\Controller::select() does only seem to accept array, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
35
        $authManager = Yii::$app->getAuthManager();
36
        $role = $authManager->getRole($roleName);
37
38
        // Проверяем есть ли уже такая роль у пользователя
39
        $userRoles = self::getUserRoleValue($user->id);
40
        if ($userRoles === null) {
41
            $authManager->assign($role, $user->id);
42
            $this->stdout(Console::convertEncoding(Yii::t('app', 'Success!')), Console::FG_GREEN, Console::BOLD);
43
            $this->stdout(PHP_EOL);
44
        } else {
45
            $this->stdout(Console::convertEncoding(Yii::t('app', 'The user already has a role.')), Console::FG_RED, Console::BOLD);
46
            $this->stdout(PHP_EOL);
47
        }
48
    }
49
50
    /**
51
     * Removes role from user
52
     */
53
    public function actionRevoke()
54
    {
55
        $username = $this->prompt(Console::convertEncoding(Yii::t('app', 'Username:')), ['required' => true]);
0 ignored issues
show
Bug introduced by
It seems like \console\components\help...:t('app', 'Username:')) targeting console\components\helpe...sole::convertEncoding() can also be of type array; however, yii\console\Controller::prompt() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
56
        $user = $this->findModel($username);
57
        $roleName = $this->select(
58
            Console::convertEncoding(Yii::t('app', 'Role:')), ArrayHelper::merge(
0 ignored issues
show
Bug introduced by
It seems like \console\components\help...Yii::t('app', 'Role:')) targeting console\components\helpe...sole::convertEncoding() can also be of type array; however, yii\console\Controller::select() does only seem to accept string, maybe add an additional type check?

This check looks at variables that are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
59
            ['all' => Console::convertEncoding(Yii::t('app', 'All Roles'))],
60
            Console::convertEncoding(
61
                ArrayHelper::map(Yii::$app->authManager->getRolesByUser($user->id), 'name', 'description')
62
            )
63
        )
64
        );
65
        $authManager = Yii::$app->getAuthManager();
66
        if ($roleName == 'all') {
67
            $authManager->revokeAll($user->id);
68
        } else {
69
            $role = $authManager->getRole($roleName);
70
            $authManager->revoke($role, $user->id);
71
        }
72
        $this->stdout(Console::convertEncoding(Yii::t('app', 'Done!')), Console::FG_GREEN, Console::BOLD);
73
        $this->stdout(PHP_EOL);
74
    }
75
76
    /**
77
     * @param null $user_id
78
     * @return mixed|null
79
     */
80
    public function getUserRoleValue($user_id = null)
81
    {
82
        if ($role = Yii::$app->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
     * @param string $username
97
     * @return \modules\users\models\User the loaded model
98
     * @throws \yii\console\Exception if the model cannot be found
99
     */
100 View Code Duplication
    private function findModel($username = '')
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
101
    {
102
        if (!empty($username)) {
103
            if ($model = User::findOne(['username' => $username])) {
0 ignored issues
show
Bug Compatibility introduced by
The expression \modules\users\models\Us...ername' => $username)); of type yii\db\ActiveRecordInterface|array|null adds the type array to the return on line 104 which is incompatible with the return type documented by modules\rbac\console\RolesController::findModel of type modules\users\models\User.
Loading history...
104
                return $model;
105
            }
106
        }
107
        throw new Exception(
108
            Console::convertEncoding(
109
                Yii::t('app', 'User "{:Username}" not found', [':Username' => $username])
110
            )
111
        );
112
    }
113
}
114