Completed
Push — master ( ed3d70...265f24 )
by vistart
03:56
created

Member::tableName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
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\Role;
17
use rhosocial\user\User;
18
use rhosocial\organization\rbac\roles\DepartmentAdmin;
19
use rhosocial\organization\rbac\roles\DepartmentCreator;
20
use rhosocial\organization\rbac\roles\OrganizationAdmin;
21
use rhosocial\organization\rbac\roles\OrganizationCreator;
22
use rhosocial\organization\queries\OrganizationQuery;
23
use rhosocial\organization\queries\MemberQuery;
24
use Yii;
25
use yii\base\InvalidValueException;
26
use yii\db\IntegrityException;
27
28
/**
29
 * Organization member.
30
 *
31
 * @property string $organization_guid
32
 * @property string $user_guid store guid of user who represents this member.
33
 * @property string $nickname
34
 * @property string $role
35
 * @property string $position
36
 * @property string $description
37
 * 
38
 * @property string $department_guid
39
 * @property string $member_guid
40
 * @property User $memberUser
41
 *
42
 * @version 1.0
43
 * @author vistart <[email protected]>
44
 */
45
class Member extends BaseBlameableModel
46
{
47
    public $createdByAttribute = 'organization_guid';
48
    public $updatedByAttribute = false;
49
    public $hostClass = Organization::class;
50
51
    public $memberAttribute = 'user_guid';
52
    public $memberUserClass = User::class;
53
    public $contentAttribute = 'nickname';
54
    private $noInitMemberUser;
55
    /**
56
     * @return User
57
     */
58 31
    protected function getNoInitMemberUser()
59
    {
60 31
        if (!$this->noInitMemberUser) {
61 31
            $class = $this->memberUserClass;
62 31
            $this->noInitMemberUser = $class::buildNoInitModel();
63
        }
64 31
        return $this->noInitMemberUser;
65
    }
66
67
    /**
68
     * @inheritdoc
69
     */
70 31
    public function init()
71
    {
72 31
        if (!is_string($this->queryClass)) {
73 31
            $this->queryClass = MemberQuery::class;
74
        }
75 31
        if ($this->skipInit) {
76 31
            return;
77
        }
78 31
        parent::init();
79 31
    }
80
81
    public $descriptionAttribute = 'description';
82
83 31
    public function getMemberUserRules()
84
    {
85
        return [
86 31
            [$this->memberAttribute, 'required'],
87 31
            [$this->memberAttribute, 'string', 'max' => 36],
88
        ];
89
    }
90
91 31
    public function getMemberRoleRules()
92
    {
93
        return [
94 31
            ['role', 'string', 'max' => 255],
95
        ];
96
    }
97
98 31
    public function getMemberPositionRules()
99
    {
100
        return [
101 31
            ['position', 'default', 'value' => ''],
102
            ['position', 'string', 'max' => 255],
103
        ];
104
    }
105
106
    /**
107
     * Set member user.
108
     * @param User|string|integer $user
109
     */
110 31
    public function setMemberUser($user)
111
    {
112 31
        $class = $this->memberUserClass;
113 31
        if (is_numeric($user)) {
114
            $user = $class::find()->id($user)->one();
115
        }
116 31
        if ($user instanceof $class) {
117 31
            $user = $user->getGUID();
118
        }
119 31
        $this->{$this->memberAttribute} = $user;
120 31
    }
121
122 31
    public function getMemberUser()
123
    {
124 31
        return $this->hasOne($this->memberUserClass, [$this->getNoInitMemberUser()->guidAttribute => $this->memberAttribute]);
125
    }
126
127
    /**
128
     * Get Organization Query.
129
     * Alias of `getHost` method.
130
     * @return OrganizationQuery
131
     */
132 21
    public function getOrganization()
133
    {
134 21
        return $this->getHost();
135
    }
136
137
    /**
138
     * Set Organization.
139
     * @param BaseOrganization $organization
140
     * @return boolean
141
     */
142 31
    public function setOrganization($organization)
143
    {
144 31
        return $this->setHost($organization);
145
    }
146
147
    /**
148
     * Assign role.
149
     * The setting role operation will not take effect immediately. You should
150
     * wrap this method and the subsequent save operations together into a
151
     * transaction, in order to ensure data cosistency.
152
     * @param Role $role
153
     */
154 31
    public function assignRole($role)
155
    {
156 31
        $user = $this->memberUser;
157 31
        if (!$user) {
158
            throw new InvalidValueException('Invalid User');
159
        }
160 31
        $assignment = Yii::$app->authManager->getAssignment($role->name, $user);
161 31
        if (!$assignment) {
162 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...
163
        }
164 31
        return $this->setRole($role);
165
    }
166
167
    /**
168
     * Set role.
169
     * @param Role $role
170
     * @return boolean
171
     */
172 31
    public function setRole($role = null)
173
    {
174 31
        if (empty($role)) {
175 18
            $role = '';
176
        }
177 31
        if ($role instanceof Role) {
178 31
            $role = $role->name;
179
        }
180 31
        $this->role = $role;
181 31
    }
182
183
    /**
184
     * Revoke role.
185
     * @param Role $role
186
     */
187 18
    public function revokeRole($role)
188
    {
189 18
        $user = $this->memberUser;
190 18
        if (!$user) {
191
            throw new InvalidValueException('Invalid User');
192
        }
193 18
        $transaction = Yii::$app->db->beginTransaction();
194
        try {
195 18
            $assignment = Yii::$app->authManager->getAssignment($role->name, $user);
196 18
            if ($assignment) {
197 18
                $count = (int)($user->getOfMembers()->role($role->name)->count());
198 18
                if ($count == 1) {
199 16
                    Yii::$app->authManager->revoke($role, $user);
200
                }
201
            }
202 18
            $this->setRole();
203 18
            if (!$this->save()) {
204
                throw new IntegrityException('Save failed.');
205
            }
206 18
            $transaction->commit();
207
        } catch (\Exception $ex) {
208
            $transaction->rollBack();
209
            Yii::error($ex->getMessage(), __METHOD__);
210
            throw $ex;
211
        }
212 18
        return true;
213
    }
214
215 31
    public function rules()
216
    {
217 31
        return array_merge($this->getMemberUserRules(), $this->getMemberRoleRules(), $this->getMemberPositionRules(), parent::rules());
218
    }
219
220
    /**
221
     * @inheritdoc
222
     */
223 31
    public static function tableName()
224
    {
225 31
        return '{{%organization_member}}';
226
    }
227
228
    /**
229
     * @inheritdoc
230
     */
231 1
    public function attributeLabels()
232
    {
233
        return [
234 1
            'guid' => Yii::t('app', 'GUID'),
235 1
            'id' => Yii::t('app', 'ID'),
236 1
            'organization_guid' => Yii::t('app', 'Organization GUID'),
237 1
            'user_guid' => Yii::t('app', 'User GUID'),
238 1
            'nickname' => Yii::t('app', 'Nickname'),
239 1
            'role' => Yii::t('app', 'Role'),
240 1
            'position' => Yii::t('app', 'Position'),
241 1
            'description' => Yii::t('app', 'Description'),
242 1
            'ip' => Yii::t('app', 'IP'),
243 1
            'ip_type' => Yii::t('app', 'IP Address Type'),
244 1
            'created_at' => Yii::t('app', 'Create Time'),
245 1
            'updated_at' => Yii::t('app', 'Update Time'),
246
        ];
247
    }
248
249 3
    public function isDepartmentAdministrator()
250
    {
251 3
        return $this->role == (new DepartmentAdmin())->name;
252
    }
253
    
254 8
    public function isDepartmentCreator()
255
    {
256 8
        return $this->role == (new DepartmentCreator())->name;
257
    }
258
259 3
    public function isOrganizationAdministrator()
260
    {
261 3
        return $this->role == (new OrganizationAdmin())->name;
262
    }
263
    
264 8
    public function isOrganizationCreator()
265
    {
266 8
        return $this->role == (new OrganizationCreator())->name;
267
    }
268
269
    /**
270
     * Check whether current member is administrator.
271
     * @return boolean
272
     */
273 3
    public function isAdministrator()
274
    {
275 3
        return $this->isDepartmentAdministrator() || $this->isOrganizationAdministrator();
276
    }
277
278
    /**
279
     * Check whether current member is creator.
280
     * @return boolean
281
     */
282 8
    public function isCreator()
283
    {
284 8
        return $this->isDepartmentCreator() || $this->isOrganizationCreator();
285
    }
286
287
    /**
288
     * We think it a `member` if `role` property is empty.
289
     * @return boolean
290
     */
291 2
    public function isOnlyMember()
292
    {
293 2
        return empty($this->role);
294
    }
295
}
296