Passed
Push — master ( 5b0966...10e526 )
by Misbahul D
02:41
created

AuthItem   F

Complexity

Total Complexity 61

Size/Duplication

Total Lines 326
Duplicated Lines 14.11 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 0
Metric Value
wmc 61
lcom 1
cbo 11
dl 46
loc 326
rs 3.52
c 0
b 0
f 0

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 12 3
A rules() 0 13 2
A checkUnique() 0 13 3
A checkRule() 0 17 4
A attributeLabels() 0 10 1
A getIsNewRecord() 0 4 1
A find() 0 9 2
B save() 0 30 7
B addChildren() 23 23 7
B removeChildren() 23 23 7
C getItems() 0 28 12
B getUsers() 0 48 9
A getItem() 0 4 1
A getTypeName() 0 12 2

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AuthItem often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AuthItem, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace mdm\admin\models;
4
5
use mdm\admin\components\Configs;
6
use mdm\admin\components\Helper;
7
use mdm\admin\controllers\AssignmentController;
8
use mdm\admin\Module;
9
use Yii;
10
use yii\base\Model;
11
use yii\helpers\Json;
12
use yii\helpers\Url;
13
use yii\rbac\Item;
14
use yii\rbac\Rule;
15
16
/**
17
 * This is the model class for table "tbl_auth_item".
18
 *
19
 * @property string $name
20
 * @property integer $type
21
 * @property string $description
22
 * @property string $ruleName
23
 * @property string $data
24
 *
25
 * @property Item $item
26
 *
27
 * @author Misbahul D Munir <[email protected]>
28
 * @since 1.0
29
 */
30
class AuthItem extends Model
31
{
32
    public $name;
33
    public $type;
34
    public $description;
35
    public $ruleName;
36
    public $data;
37
38
    /**
39
     * @var Item
40
     */
41
    private $_item;
42
43
    /**
44
     * Initialize object
45
     * @param Item  $item
46
     * @param array $config
47
     */
48
    public function __construct($item = null, $config = [])
49
    {
50
        $this->_item = $item;
51
        if ($item !== null) {
52
            $this->name = $item->name;
53
            $this->type = $item->type;
54
            $this->description = $item->description;
55
            $this->ruleName = $item->ruleName;
56
            $this->data = $item->data === null ? null : Json::encode($item->data);
57
        }
58
        parent::__construct($config);
59
    }
60
61
    /**
62
     * @inheritdoc
63
     */
64
    public function rules()
65
    {
66
        return [
67
            [['ruleName'], 'checkRule'],
68
            [['name', 'type'], 'required'],
69
            [['name'], 'checkUnique', 'when' => function () {
70
                    return $this->isNewRecord || ($this->_item->name != $this->name);
0 ignored issues
show
Documentation introduced by
The property isNewRecord does not exist on object<mdm\admin\models\AuthItem>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
71
                }],
72
            [['type'], 'integer'],
73
            [['description', 'data', 'ruleName'], 'default'],
74
            [['name'], 'string', 'max' => 64],
75
        ];
76
    }
77
78
    /**
79
     * Check role is unique
80
     */
81
    public function checkUnique()
82
    {
83
        $authManager = Configs::authManager();
84
        $value = $this->name;
85
        if ($authManager->getRole($value) !== null || $authManager->getPermission($value) !== null) {
86
            $message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
87
            $params = [
88
                'attribute' => $this->getAttributeLabel('name'),
89
                'value' => $value,
90
            ];
91
            $this->addError('name', Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
92
        }
93
    }
94
95
    /**
96
     * Check for rule
97
     */
98
    public function checkRule()
99
    {
100
        $name = $this->ruleName;
101
        if (!Configs::authManager()->getRule($name)) {
102
            try {
103
                $rule = Yii::createObject($name);
104
                if ($rule instanceof Rule) {
105
                    $rule->name = $name;
106
                    Configs::authManager()->add($rule);
107
                } else {
108
                    $this->addError('ruleName', Yii::t('rbac-admin', 'Invalid rule "{value}"', ['value' => $name]));
109
                }
110
            } catch (\Exception $exc) {
111
                $this->addError('ruleName', Yii::t('rbac-admin', 'Rule "{value}" does not exists', ['value' => $name]));
112
            }
113
        }
114
    }
115
116
    /**
117
     * @inheritdoc
118
     */
119
    public function attributeLabels()
120
    {
121
        return [
122
            'name' => Yii::t('rbac-admin', 'Name'),
123
            'type' => Yii::t('rbac-admin', 'Type'),
124
            'description' => Yii::t('rbac-admin', 'Description'),
125
            'ruleName' => Yii::t('rbac-admin', 'Rule Name'),
126
            'data' => Yii::t('rbac-admin', 'Data'),
127
        ];
128
    }
129
130
    /**
131
     * Check if is new record.
132
     * @return boolean
133
     */
134
    public function getIsNewRecord()
135
    {
136
        return $this->_item === null;
137
    }
138
139
    /**
140
     * Find role
141
     * @param string $id
142
     * @return null|\self
143
     */
144
    public static function find($id)
145
    {
146
        $item = Configs::authManager()->getRole($id);
147
        if ($item !== null) {
148
            return new self($item);
149
        }
150
151
        return null;
152
    }
153
154
    /**
155
     * Save role to [[\yii\rbac\authManager]]
156
     * @return boolean
157
     */
158
    public function save()
159
    {
160
        if ($this->validate()) {
161
            $manager = Configs::authManager();
162
            if ($this->_item === null) {
163
                if ($this->type == Item::TYPE_ROLE) {
164
                    $this->_item = $manager->createRole($this->name);
165
                } else {
166
                    $this->_item = $manager->createPermission($this->name);
167
                }
168
                $isNew = true;
169
            } else {
170
                $isNew = false;
171
                $oldName = $this->_item->name;
172
            }
173
            $this->_item->name = $this->name;
174
            $this->_item->description = $this->description;
175
            $this->_item->ruleName = $this->ruleName;
176
            $this->_item->data = $this->data === null || $this->data === '' ? null : Json::decode($this->data);
177
            if ($isNew) {
178
                $manager->add($this->_item);
0 ignored issues
show
Documentation introduced by
$this->_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...
179
            } else {
180
                $manager->update($oldName, $this->_item);
0 ignored issues
show
Bug introduced by
The variable $oldName does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Documentation introduced by
$this->_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...
181
            }
182
            Helper::invalidate();
183
            return true;
184
        } else {
185
            return false;
186
        }
187
    }
188
189
    /**
190
     * Adds an item as a child of another item.
191
     * @param array $items
192
     * @return int
193
     */
194 View Code Duplication
    public function addChildren($items)
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...
195
    {
196
        $manager = Configs::authManager();
197
        $success = 0;
198
        if ($this->_item) {
199
            foreach ($items as $name) {
200
                $child = $manager->getPermission($name);
201
                if ($this->type == Item::TYPE_ROLE && $child === null) {
202
                    $child = $manager->getRole($name);
203
                }
204
                try {
205
                    $manager->addChild($this->_item, $child);
0 ignored issues
show
Bug introduced by
It seems like $child can also be of type null; however, yii\rbac\ManagerInterface::addChild() does only seem to accept object<yii\rbac\Item>, 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...
206
                    $success++;
207
                } catch (\Exception $exc) {
208
                    Yii::error($exc->getMessage(), __METHOD__);
209
                }
210
            }
211
        }
212
        if ($success > 0) {
213
            Helper::invalidate();
214
        }
215
        return $success;
216
    }
217
218
    /**
219
     * Remove an item as a child of another item.
220
     * @param array $items
221
     * @return int
222
     */
223 View Code Duplication
    public function removeChildren($items)
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...
224
    {
225
        $manager = Configs::authManager();
226
        $success = 0;
227
        if ($this->_item !== null) {
228
            foreach ($items as $name) {
229
                $child = $manager->getPermission($name);
230
                if ($this->type == Item::TYPE_ROLE && $child === null) {
231
                    $child = $manager->getRole($name);
232
                }
233
                try {
234
                    $manager->removeChild($this->_item, $child);
0 ignored issues
show
Bug introduced by
It seems like $child can also be of type null; however, yii\rbac\ManagerInterface::removeChild() does only seem to accept object<yii\rbac\Item>, 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...
235
                    $success++;
236
                } catch (\Exception $exc) {
237
                    Yii::error($exc->getMessage(), __METHOD__);
238
                }
239
            }
240
        }
241
        if ($success > 0) {
242
            Helper::invalidate();
243
        }
244
        return $success;
245
    }
246
247
    /**
248
     * Get items
249
     * @return array
250
     */
251
    public function getItems()
252
    {
253
        $manager = Configs::authManager();
254
        $advanced = Configs::instance()->advanced;
255
        $available = [];
256
        if ($this->type == Item::TYPE_ROLE) {
257
            foreach (array_keys($manager->getRoles()) as $name) {
258
                $available[$name] = 'role';
259
            }
260
        }
261
        foreach (array_keys($manager->getPermissions()) as $name) {
262
            $available[$name] = $name[0] == '/' || $advanced && $name[0] == '@' ? 'route' : 'permission';
263
        }
264
265
        $assigned = [];
266
        foreach ($manager->getChildren($this->_item->name) as $item) {
267
            $assigned[$item->name] = $item->type == 1 ? 'role' : ($item->name[0] == '/' || $advanced && $item->name[0] == '@'
268
                    ? 'route' : 'permission');
269
            unset($available[$item->name]);
270
        }
271
        unset($available[$this->name]);
272
        ksort($available);
273
        ksort($assigned);
274
        return [
275
            'available' => $available,
276
            'assigned' => $assigned,
277
        ];
278
    }
279
280
    public function getUsers()
281
    {
282
        $module = Yii::$app->controller->module;
283
        if (!$module || !$module instanceof Module) {
284
            return [];
285
        }
286
        $ctrl = $module->createController('assignment');
287
        $result = [];
288
        if ($ctrl && $ctrl[0] instanceof AssignmentController) {
289
            $ctrl = $ctrl[0];
290
            $class = $ctrl->userClassName;
291
            $idField = $ctrl->idField;
292
            $usernameField = $ctrl->usernameField;
293
294
            $manager = Configs::authManager();
295
            $ids = $manager->getUserIdsByRole($this->name);
296
297
            $provider = new \yii\data\ArrayDataProvider([
298
                'allModels' => $ids,
299
                'pagination' => [
300
                    'pageSize' => Configs::userRolePageSize(),
301
                ]
302
            ]);
303
            $users = $class::find()
304
                    ->select(['id' => $idField, 'username' => $usernameField])
305
                    ->where([$idField => $provider->getModels()])
306
                    ->asArray()->all();
307
308
            $route = '/' . $ctrl->uniqueId . '/view';
309
            foreach ($users as &$row) {
310
                $row['link'] = Url::to([$route, 'id' => $row['id']]);
311
            }
312
            $result['users'] = $users;
313
            $currentPage = $provider->pagination->getPage();
314
            $pageCount = $provider->pagination->getPageCount();
315
            if ($pageCount > 0) {
316
                $result['first'] = 0;
317
                $result['last'] = $pageCount - 1;
318
                if ($currentPage > 0) {
319
                    $result['prev'] = $currentPage - 1;
320
                }
321
                if ($currentPage < $pageCount - 1) {
322
                    $result['next'] = $currentPage + 1;
323
                }
324
            }
325
        }
326
        return $result;
327
    }
328
329
    /**
330
     * Get item
331
     * @return Item
332
     */
333
    public function getItem()
334
    {
335
        return $this->_item;
336
    }
337
338
    /**
339
     * Get type name
340
     * @param  mixed $type
341
     * @return string|array
342
     */
343
    public static function getTypeName($type = null)
344
    {
345
        $result = [
346
            Item::TYPE_PERMISSION => 'Permission',
347
            Item::TYPE_ROLE => 'Role',
348
        ];
349
        if ($type === null) {
350
            return $result;
351
        }
352
353
        return $result[$type];
354
    }
355
}
356