Completed
Push — master ( 96ea51...824082 )
by Andrii
05:07 queued 03:08
created

AuthManager::setCurrentUserRole()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.25

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 6
cts 8
cp 0.75
rs 9.2
c 0
b 0
f 0
cc 4
eloc 5
nc 5
nop 0
crap 4.25
1
<?php
2
3
/*
4
 * RBAC implementation for HiPanel
5
 *
6
 * @link      https://github.com/hiqdev/hipanel-rbac
7
 * @package   hipanel-rbac
8
 * @license   BSD-3-Clause
9
 * @copyright Copyright (c) 2016, HiQDev (http://hiqdev.com/)
10
 */
11
12
namespace hipanel\rbac;
13
14
use yii\base\InvalidParamException;
15
use yii\rbac\Item;
16
use Yii;
17
18
/**
19
 * HiPanel AuthManager.
20
 *
21
 * @author Andrii Vasyliev <[email protected]>
22
 */
23
class AuthManager extends \yii\rbac\PhpManager
24
{
25
    public $itemFile       = '@hipanel/rbac/files/items.php';
26
    public $ruleFile       = '@hipanel/rbac/files/rules.php';
27
    public $assignmentFile = '@hipanel/rbac/files/assignments.php';
28
29
    /**
30
     * Set permission.
31
     * @param string $name
32
     * @param string $description
33
     * @return Item
34
     */
35 3
    public function setPermission($name, $description = null)
36
    {
37 3
        return $this->setItem('permission', $name, $description);
38
    }
39
40
    /**
41
     * Set role.
42
     * @param string $name
43
     * @param string $description
44
     * @return Item
45
     */
46 3
    public function setRole($name, $description = null)
47
    {
48 3
        return $this->setItem('role', $name, $description);
49
    }
50
51
    /**
52
     * Set item by type and name.
53
     * Created if not exists else updates.
54
     * @param string $type
55
     * @param string $name
56
     * @param string $description
57
     * @return Item
58
     */
59 3
    public function setItem($type, $name, $description = null)
60
    {
61 3
        $item = $this->getItem($name) ?: $this->createItem($type, $name);
62 3
        if ($description) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $description of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
63
            $item->description = $description;
64
        }
65 3
        $this->add($item);
0 ignored issues
show
Documentation introduced by
$item is of type object<yii\rbac\Item>, but the function expects a object<yii\rbac\Role>|ob...>|object<yii\rbac\Rule>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
66
67 3
        return $item;
68
    }
69
70
    /**
71
     * Create item by type and name.
72
     * @param string $type
73
     * @param string $name
74
     * @throws InvalidParamException
75
     * @return Item
76
     */
77 3
    public function createItem($type, $name)
78
    {
79 3
        if ('role' === $type) {
80 3
            return $this->createRole($name);
81 3
        } elseif ('permission' === $type) {
82 3
            return $this->createPermission($name);
83
        } else {
84
            throw new InvalidParamException('Creating unsupported item type: ' . $type);
85
        }
86
    }
87
88
    /**
89
     * Set child.
90
     * @param string|Item $parent
91
     * @param string|Item $child
92
     * @return bool
93
     */
94 3
    public function setChild($parent, $child)
95
    {
96 3 View Code Duplication
        if (is_string($parent)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
97 3
            $name   = $parent;
98 3
            $parent = $this->getItem($parent);
99 3
            if (is_null($parent)) {
100
                throw new InvalidParamException("Unknown parent:$name at setChild");
101
            }
102 3
        }
103 3 View Code Duplication
        if (is_string($child)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
104 3
            $name  = $child;
105 3
            $child = $this->getItem($child);
106 3
            if (is_null($child)) {
107
                throw new InvalidParamException("Unknown child:$name at setChild");
108
            }
109 3
        }
110 3
        if (isset($this->children[$parent->name][$child->name])) {
111
            return false;
112
        }
113
114 3
        return $this->addChild($parent, $child);
115
    }
116
117
    /**
118
     * Assigns a role to a user.
119
     * @param Role $role
120
     * @param string|integer $userId the user ID (see [[\yii\web\User::id]])
121
     * @throws \Exception when given wrong role name or the role has already been assigned to the user
122
     * @return Assignment the role assignment information
123
     */
124 6
    public function setAssignment($role, $userId)
125
    {
126 6 View Code Duplication
        if (is_string($role)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
127 6
            $name = $role;
128 6
            $role = $this->getRole($role);
129 6
            if (is_null($role)) {
130
                throw new InvalidParamException("Unknown role:$name at setAssignment");
131
            }
132 6
        }
133 6
        if (isset($this->assignments[$userId][$role->name])) {
134
            return false;
135
        }
136
137 6
        return $this->assign($role, $userId);
0 ignored issues
show
Bug introduced by
It seems like $role defined by $this->getRole($role) on line 128 can also be of type object<yii\rbac\Item>; however, yii\rbac\PhpManager::assign() does only seem to accept object<yii\rbac\Role>, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
138
    }
139
140 6
    public function getRoles()
141
    {
142 6
        return $this->getItems(Item::TYPE_ROLE);
143
    }
144
145
    public function getPermissions()
146
    {
147
        return $this->getItems(Item::TYPE_PERMISSION);
148
    }
149
150
    public function getAllAssignments()
151
    {
152
        return $this->assignments;
153
    }
154
155
    /**
156
     * We don't keep all the assignments, only basic.
157
     * @see forceSaveAssignments
158
     */
159 6
    protected function saveAssignments()
160
    {
161 6
    }
162
163
    /**
164
     * Create only basic assignments before saving.
165
     */
166 3
    public function saveBasicAssignments()
167
    {
168 3
        parent::saveAssignments();
0 ignored issues
show
Comprehensibility Bug introduced by
It seems like you call parent on a different method (saveAssignments() instead of saveBasicAssignments()). Are you sure this is correct? If so, you might want to change this to $this->saveAssignments().

This check looks for a call to a parent method whose name is different than the method from which it is called.

Consider the following code:

class Daddy
{
    protected function getFirstName()
    {
        return "Eidur";
    }

    protected function getSurName()
    {
        return "Gudjohnsen";
    }
}

class Son
{
    public function getFirstName()
    {
        return parent::getSurname();
    }
}

The getFirstName() method in the Son calls the wrong method in the parent class.

Loading history...
169 3
    }
170
171 6
    public function checkAccess($userId, $permission, $params = [])
172
    {
173 6
        $this->setCurrentUserRole();
174 6
        if ($userId === $this->getIdentity()->id) {
175
            $userId = $this->getIdentity()->username;
176
        }
177
178 6
        return parent::checkAccess($userId, $permission, $params);
179
    }
180
181
    protected $_currentUserRole;
182
183 6
    public function setCurrentUserRole()
184
    {
185 6
        if ($this->_currentUserRole === null) {
186 6
            $this->_currentUserRole = $this->getIdentity()->type ?: '';
187 6
            if ($this->_currentUserRole) {
188
                $this->setAssignment($this->_currentUserRole, $this->getIdentity()->username);
189
            }
190 6
        }
191 6
    }
192
193 6
    public function getIdentity()
194
    {
195 6
        return Yii::$app->user->identity;
196
    }
197
}
198