Passed
Push — master ( 265f24...4533bd )
by vistart
03:55
created

Member::attributeLabels()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 13
cts 13
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 14
nc 1
nop 0
crap 1
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link https://vistart.me/
9
 * @copyright Copyright (c) 2016 - 2017 vistart
10
 * @license https://vistart.me/license/
11
 */
12
13
namespace rhosocial\organization;
14
15
use rhosocial\base\models\models\BaseBlameableModel;
16
use rhosocial\user\rbac\Item;
17
use rhosocial\user\rbac\Role;
18
use rhosocial\user\User;
19
use rhosocial\organization\rbac\roles\DepartmentAdmin;
20
use rhosocial\organization\rbac\roles\DepartmentCreator;
21
use rhosocial\organization\rbac\roles\OrganizationAdmin;
22
use rhosocial\organization\rbac\roles\OrganizationCreator;
23
use rhosocial\organization\queries\OrganizationQuery;
24
use rhosocial\organization\queries\MemberQuery;
25
use Yii;
26
use yii\base\InvalidValueException;
27
use yii\db\IntegrityException;
28
29
/**
30
 * Organization member.
31
 *
32
 * @property string $organization_guid
33
 * @property string $user_guid store guid of user who represents this member.
34
 * @property string $nickname
35
 * @property string $role
36
 * @property string $position
37
 * @property string $description
38
 * 
39
 * @property string $department_guid
40
 * @property string $member_guid
41
 * @property User $memberUser
42
 *
43
 * @version 1.0
44
 * @author vistart <[email protected]>
45
 */
46
class Member extends BaseBlameableModel
47
{
48
    public $createdByAttribute = 'organization_guid';
49
    public $updatedByAttribute = false;
50
    public $hostClass = Organization::class;
51
52
    public $memberAttribute = 'user_guid';
53
    public $memberUserClass = User::class;
54
    public $contentAttribute = 'nickname';
55
    private $noInitMemberUser;
56
    /**
57
     * @return User
58
     */
59 31
    protected function getNoInitMemberUser()
60
    {
61 31
        if (!$this->noInitMemberUser) {
62 31
            $class = $this->memberUserClass;
63 31
            $this->noInitMemberUser = $class::buildNoInitModel();
64
        }
65 31
        return $this->noInitMemberUser;
66
    }
67
68
    /**
69
     * @inheritdoc
70
     */
71 31
    public function init()
72
    {
73 31
        if (!is_string($this->queryClass)) {
74 31
            $this->queryClass = MemberQuery::class;
75
        }
76 31
        if ($this->skipInit) {
77 31
            return;
78
        }
79 31
        parent::init();
80 31
    }
81
82
    public $descriptionAttribute = 'description';
83
84 31
    public function getMemberUserRules()
85
    {
86
        return [
87 31
            [$this->memberAttribute, 'required'],
88 31
            [$this->memberAttribute, 'string', 'max' => 36],
89
        ];
90
    }
91
92 31
    public function getMemberRoleRules()
93
    {
94
        return [
95 31
            ['role', 'string', 'max' => 255],
96
        ];
97
    }
98
99 31
    public function getMemberPositionRules()
100
    {
101
        return [
102 31
            ['position', 'default', 'value' => ''],
103
            ['position', 'string', 'max' => 255],
104
        ];
105
    }
106
107
    /**
108
     * Set member user.
109
     * @param User|string|integer $user
110
     */
111 31
    public function setMemberUser($user)
112
    {
113 31
        $class = $this->memberUserClass;
114 31
        if (is_numeric($user)) {
115
            $user = $class::find()->id($user)->one();
116
        }
117 31
        if ($user instanceof $class) {
118 31
            $user = $user->getGUID();
119
        }
120 31
        $this->{$this->memberAttribute} = $user;
121 31
    }
122
123 31
    public function getMemberUser()
124
    {
125 31
        return $this->hasOne($this->memberUserClass, [$this->getNoInitMemberUser()->guidAttribute => $this->memberAttribute]);
126
    }
127
128
    /**
129
     * Get Organization Query.
130
     * Alias of `getHost` method.
131
     * @return OrganizationQuery
132
     */
133 21
    public function getOrganization()
134
    {
135 21
        return $this->getHost();
136
    }
137
138
    /**
139
     * Set Organization.
140
     * @param BaseOrganization $organization
141
     * @return boolean
142
     */
143 31
    public function setOrganization($organization)
144
    {
145 31
        return $this->setHost($organization);
146
    }
147
148
    /**
149
     * Assign role.
150
     * The setting role operation will not take effect immediately. You should
151
     * wrap this method and the subsequent save operations together into a
152
     * transaction, in order to ensure data cosistency.
153
     * @param Role $role
154
     */
155 31
    public function assignRole($role)
156
    {
157 31
        $user = $this->memberUser;
158 31
        if (!$user) {
159
            throw new InvalidValueException('Invalid User');
160
        }
161 31
        if ($role instanceof Item) {
162
            $role = $role->name;
163
        }
164 31
        $assignment = Yii::$app->authManager->getAssignment($role, $user);
165 31
        if (!$assignment) {
166 31
            $assignment = Yii::$app->authManager->assign($role, $user->getGUID());
0 ignored issues
show
Unused Code introduced by
$assignment is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
167
        }
168 31
        return $this->setRole($role);
0 ignored issues
show
Documentation introduced by
$role is of type string, but the function expects a object<rhosocial\user\rbac\Role>|null.

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...
169
    }
170
171
    /**
172
     * Set role.
173
     * @param Role $role
174
     * @return boolean
175
     */
176 31
    public function setRole($role = null)
177
    {
178 31
        if (empty($role)) {
179 18
            $role = '';
180
        }
181 31
        if ($role instanceof Item) {
182
            $role = $role->name;
183
        }
184 31
        $this->role = $role;
185 31
    }
186
187
    /**
188
     * Revoke role.
189
     * @param Role $role
190
     */
191 18
    public function revokeRole($role)
192
    {
193 18
        $user = $this->memberUser;
194 18
        if (!$user) {
195
            throw new InvalidValueException('Invalid User');
196
        }
197 18
        if ($role instanceof Item) {
198
            $role = $role->name;
199
        }
200 18
        $transaction = Yii::$app->db->beginTransaction();
201
        try {
202 18
            $assignment = Yii::$app->authManager->getAssignment($role, $user);
203 18
            if ($assignment) {
204 18
                $count = (int)($user->getOfMembers()->role($role)->count());
205 18
                if ($count == 1) {
206 16
                    Yii::$app->authManager->revoke($role, $user);
207
                }
208
            }
209 18
            $this->setRole();
210 18
            if (!$this->save()) {
211
                throw new IntegrityException('Save failed.');
212
            }
213 18
            $transaction->commit();
214
        } catch (\Exception $ex) {
215
            $transaction->rollBack();
216
            Yii::error($ex->getMessage(), __METHOD__);
217
            throw $ex;
218
        }
219 18
        return true;
220
    }
221
222 31
    public function rules()
223
    {
224 31
        return array_merge($this->getMemberUserRules(), $this->getMemberRoleRules(), $this->getMemberPositionRules(), parent::rules());
225
    }
226
227
    /**
228
     * @inheritdoc
229
     */
230 31
    public static function tableName()
231
    {
232 31
        return '{{%organization_member}}';
233
    }
234
235
    /**
236
     * @inheritdoc
237
     */
238 1
    public function attributeLabels()
239
    {
240
        return [
241 1
            'guid' => Yii::t('app', 'GUID'),
242 1
            'id' => Yii::t('app', 'ID'),
243 1
            'organization_guid' => Yii::t('app', 'Organization GUID'),
244 1
            'user_guid' => Yii::t('app', 'User GUID'),
245 1
            'nickname' => Yii::t('app', 'Nickname'),
246 1
            'role' => Yii::t('app', 'Role'),
247 1
            'position' => Yii::t('app', 'Position'),
248 1
            'description' => Yii::t('app', 'Description'),
249 1
            'ip' => Yii::t('app', 'IP'),
250 1
            'ip_type' => Yii::t('app', 'IP Address Type'),
251 1
            'created_at' => Yii::t('app', 'Create Time'),
252 1
            'updated_at' => Yii::t('app', 'Update Time'),
253
        ];
254
    }
255
256 3
    public function isDepartmentAdministrator()
257
    {
258 3
        return $this->role == (new DepartmentAdmin)->name;
259
    }
260
    
261 1
    public function isDepartmentCreator()
262
    {
263 1
        return $this->role == (new DepartmentCreator)->name;
264
    }
265
266 3
    public function isOrganizationAdministrator()
267
    {
268 3
        return $this->role == (new OrganizationAdmin)->name;
269
    }
270
    
271 1
    public function isOrganizationCreator()
272
    {
273 1
        return $this->role == (new OrganizationCreator)->name;
274
    }
275
276
    /**
277
     * Check whether current member is administrator.
278
     * @return boolean
279
     */
280 3
    public function isAdministrator()
281
    {
282 3
        return $this->isDepartmentAdministrator() || $this->isOrganizationAdministrator();
283
    }
284
285
    /**
286
     * Check whether current member is creator.
287
     * @return boolean
288
     */
289 1
    public function isCreator()
290
    {
291 1
        return $this->isDepartmentCreator() || $this->isOrganizationCreator();
292
    }
293
294
    /**
295
     * We think it a `member` if `role` property is empty.
296
     * @return boolean
297
     */
298 2
    public function isOnlyMember()
299
    {
300 2
        return empty($this->role);
301
    }
302
}
303