Passed
Push — master ( 6e4772...b11769 )
by vistart
04:42
created

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