Completed
Push — master ( ceb93d...c5ee5e )
by Misbahul D
05:49 queued 03:43
created

AuthItem::checkUnique()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 13
rs 9.4285
cc 3
eloc 9
nc 2
nop 0
1
<?php
2
3
namespace mdm\admin\models;
4
5
use mdm\admin\components\Configs;
6
use mdm\admin\components\Helper;
7
use Yii;
8
use yii\base\Model;
9
use yii\helpers\Json;
10
use yii\rbac\Item;
11
12
/**
13
 * This is the model class for table "tbl_auth_item".
14
 *
15
 * @property string $name
16
 * @property integer $type
17
 * @property string $description
18
 * @property string $ruleName
19
 * @property string $data
20
 *
21
 * @property Item $item
22
 *
23
 * @author Misbahul D Munir <[email protected]>
24
 * @since 1.0
25
 */
26
class AuthItem extends Model
27
{
28
    public $name;
29
    public $type;
30
    public $description;
31
    public $ruleName;
32
    public $data;
33
    /**
34
     * @var Item
35
     */
36
    private $_item;
37
38
    /**
39
     * Initialize object
40
     * @param Item  $item
41
     * @param array $config
42
     */
43
    public function __construct($item = null, $config = [])
44
    {
45
        $this->_item = $item;
46
        if ($item !== null) {
47
            $this->name = $item->name;
48
            $this->type = $item->type;
49
            $this->description = $item->description;
50
            $this->ruleName = $item->ruleName;
51
            $this->data = $item->data === null ? null : Json::encode($item->data);
52
        }
53
        parent::__construct($config);
54
    }
55
56
    /**
57
     * @inheritdoc
58
     */
59
    public function rules()
60
    {
61
        return [
62
            [['ruleName'], 'checkRule'],
63
            [['name', 'type'], 'required'],
64
            [['name'], 'checkUnique', 'when' => function () {
65
                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...
66
            }],
67
            [['type'], 'integer'],
68
            [['description', 'data', 'ruleName'], 'default'],
69
            [['name'], 'string', 'max' => 64],
70
        ];
71
    }
72
73
    /**
74
     * Check role is unique
75
     */
76
    public function checkUnique()
77
    {
78
        $authManager = Configs::authManager();
79
        $value = $this->name;
80
        if ($authManager->getRole($value) !== null || $authManager->getPermission($value) !== null) {
81
            $message = Yii::t('yii', '{attribute} "{value}" has already been taken.');
82
            $params = [
83
                'attribute' => $this->getAttributeLabel('name'),
84
                'value' => $value,
85
            ];
86
            $this->addError('name', Yii::$app->getI18n()->format($message, $params, Yii::$app->language));
87
        }
88
    }
89
90
    /**
91
     * Check for rule
92
     */
93
    public function checkRule()
94
    {
95
        $name = $this->ruleName;
96
        if (!Configs::authManager()->getRule($name)) {
97
            try {
98
                $rule = Yii::createObject($name);
99
                if ($rule instanceof \yii\rbac\Rule) {
100
                    $rule->name = $name;
101
                    Configs::authManager()->add($rule);
102
                } else {
103
                    $this->addError('ruleName', Yii::t('rbac-admin', 'Invalid rule "{value}"', ['value' => $name]));
104
                }
105
            } catch (\Exception $exc) {
106
                $this->addError('ruleName', Yii::t('rbac-admin', 'Rule "{value}" does not exists', ['value' => $name]));
107
            }
108
        }
109
    }
110
111
    /**
112
     * @inheritdoc
113
     */
114
    public function attributeLabels()
115
    {
116
        return [
117
            'name' => Yii::t('rbac-admin', 'Name'),
118
            'type' => Yii::t('rbac-admin', 'Type'),
119
            'description' => Yii::t('rbac-admin', 'Description'),
120
            'ruleName' => Yii::t('rbac-admin', 'Rule Name'),
121
            'data' => Yii::t('rbac-admin', 'Data'),
122
        ];
123
    }
124
125
    /**
126
     * Check if is new record.
127
     * @return boolean
128
     */
129
    public function getIsNewRecord()
130
    {
131
        return $this->_item === null;
132
    }
133
134
    /**
135
     * Find role
136
     * @param string $id
137
     * @return null|\self
138
     */
139
    public static function find($id)
140
    {
141
        $item = Configs::authManager()->getRole($id);
142
        if ($item !== null) {
143
            return new self($item);
144
        }
145
146
        return null;
147
    }
148
149
    /**
150
     * Save role to [[\yii\rbac\authManager]]
151
     * @return boolean
152
     */
153
    public function save()
154
    {
155
        if ($this->validate()) {
156
            $manager = Configs::authManager();
157
            if ($this->_item === null) {
158
                if ($this->type == Item::TYPE_ROLE) {
159
                    $this->_item = $manager->createRole($this->name);
160
                } else {
161
                    $this->_item = $manager->createPermission($this->name);
162
                }
163
                $isNew = true;
164
            } else {
165
                $isNew = false;
166
                $oldName = $this->_item->name;
167
            }
168
            $this->_item->name = $this->name;
169
            $this->_item->description = $this->description;
170
            $this->_item->ruleName = $this->ruleName;
171
            $this->_item->data = $this->data === null || $this->data === '' ? null : Json::decode($this->data);
172
            if ($isNew) {
173
                $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...
174
            } else {
175
                $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...
176
            }
177
            Helper::invalidate();
178
            return true;
179
        } else {
180
            return false;
181
        }
182
    }
183
184
    /**
185
     * Adds an item as a child of another item.
186
     * @param array $items
187
     * @return int
188
     */
189 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...
190
    {
191
        $manager = Configs::authManager();
192
        $success = 0;
193
        if ($this->_item) {
194
            foreach ($items as $name) {
195
                $child = $manager->getPermission($name);
196
                if ($this->type == Item::TYPE_ROLE && $child === null) {
197
                    $child = $manager->getRole($name);
198
                }
199
                try {
200
                    $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...
201
                    $success++;
202
                } catch (\Exception $exc) {
203
                    Yii::error($exc->getMessage(), __METHOD__);
204
                }
205
            }
206
        }
207
        if ($success > 0) {
208
            Helper::invalidate();
209
        }
210
        return $success;
211
    }
212
213
    /**
214
     * Remove an item as a child of another item.
215
     * @param array $items
216
     * @return int
217
     */
218 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...
219
    {
220
        $manager = Configs::authManager();
221
        $success = 0;
222
        if ($this->_item !== null) {
223
            foreach ($items as $name) {
224
                $child = $manager->getPermission($name);
225
                if ($this->type == Item::TYPE_ROLE && $child === null) {
226
                    $child = $manager->getRole($name);
227
                }
228
                try {
229
                    $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...
230
                    $success++;
231
                } catch (\Exception $exc) {
232
                    Yii::error($exc->getMessage(), __METHOD__);
233
                }
234
            }
235
        }
236
        if ($success > 0) {
237
            Helper::invalidate();
238
        }
239
        return $success;
240
    }
241
242
    /**
243
     * Get items
244
     * @return array
245
     */
246
    public function getItems()
247
    {
248
        $manager = Configs::authManager();
249
        $available = [];
250
        if ($this->type == Item::TYPE_ROLE) {
251
            foreach (array_keys($manager->getRoles()) as $name) {
252
                $available[$name] = 'role';
253
            }
254
        }
255 View Code Duplication
        foreach (array_keys($manager->getPermissions()) as $name) {
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...
256
            $available[$name] = $name[0] == '/' ? 'route' : 'permission';
257
        }
258
259
        $assigned = [];
260
        foreach ($manager->getChildren($this->_item->name) as $item) {
261
            $assigned[$item->name] = $item->type == 1 ? 'role' : ($item->name[0] == '/' ? 'route' : 'permission');
262
            unset($available[$item->name]);
263
        }
264
        unset($available[$this->name]);
265
        return [
266
            'available' => $available,
267
            'assigned' => $assigned,
268
        ];
269
    }
270
271
    /**
272
     * Get item
273
     * @return Item
274
     */
275
    public function getItem()
276
    {
277
        return $this->_item;
278
    }
279
280
    /**
281
     * Get type name
282
     * @param  mixed $type
283
     * @return string|array
284
     */
285
    public static function getTypeName($type = null)
286
    {
287
        $result = [
288
            Item::TYPE_PERMISSION => 'Permission',
289
            Item::TYPE_ROLE => 'Role',
290
        ];
291
        if ($type === null) {
292
            return $result;
293
        }
294
295
        return $result[$type];
296
    }
297
}
298