Completed
Push — master ( d4a50d...32fb02 )
by vistart
08:25
created

UserRelationTrait::buildRelation()   C

Complexity

Conditions 7
Paths 13

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 7.0061

Importance

Changes 12
Bugs 0 Features 0
Metric Value
c 12
b 0
f 0
dl 0
loc 23
ccs 19
cts 20
cp 0.95
rs 6.7272
cc 7
eloc 17
nc 13
nop 2
crap 7.0061
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link http://vistart.name/
9
 * @copyright Copyright (c) 2016 vistart
10
 * @license http://vistart.name/license/
11
 */
12
13
namespace vistart\Models\traits;
14
15
use vistart\Models\models\BaseUserModel;
16
use vistart\Models\traits\MultipleBlameableTrait as mb;
17
18
/**
19
 * Relation features.
20
 * Note: Several methods associated with "inserting", "updating" and "removing" may
21
 * involve more DB operations, I strongly recommend those methods to be placed in
22
 * transaction execution, in order to ensure data consistency.
23
 * If you want to use group feature, the class used [[UserRelationGroupTrait]]
24
 * must be used coordinately.
25
 * @property array $groupGuids the guid array of all groups which owned by current relation.
26
 * @property-read array $allGroups
27
 * @property-read array $nonGroupMembers
28
 * @property-read integer $groupsCount
29
 * @property-read array $groupsRules
30
 * @property boolean $isFavorite
31
 * @property-read \vistart\Models\models\BaseUserRelationModel $opposite
32
 * @version 2.0
33
 * @author vistart <[email protected]>
34
 */
35
trait UserRelationTrait
36
{
37
    use mb {
38
        mb::addBlame as addGroup;
39
        mb::createBlame as createGroup;
40
        mb::addOrCreateBlame as addOrCreateGroup;
41
        mb::removeBlame as removeGroup;
42
        mb::removeAllBlames as removeAllGroups;
43
        mb::getBlame as getGroup;
44
        mb::getOrCreateBlame as getOrCreateGroup;
45
        mb::getBlameds as getGroupMembers;
46
        mb::getBlameGuids as getGroupGuids;
47
        mb::setBlameGuids as setGroupGuids;
48
        mb::getAllBlames as getAllGroups;
49
        mb::getNonBlameds as getNonGroupMembers;
50
        mb::getBlamesCount as getGroupsCount;
51
        mb::getMultipleBlameableAttributeRules as getGroupsRules;
52
        mb::getEmptyBlamesJson as getEmptyGroupJson;
53
    }
54
55
    /**
56
     * @var string the another party of the relation.
57
     */
58
    public $otherGuidAttribute = 'other_guid';
59
60
    /**
61
     * @var string
62
     */
63
    public $remarkAttribute = 'remark';
64
    public static $relationSingle = 0;
65
    public static $relationMutual = 1;
66
    public $relationType = 1;
67
    public $relationTypes = [
68
        0 => 'Single',
69
        1 => 'Mutual',
70
    ];
71
72
    /**
73
     * @var string the attribute name of which determines the relation type.
74
     */
75
    public $mutualTypeAttribute = 'type';
76
    public static $mutualTypeNormal = 0x00;
77
    public static $mutualTypeSuspend = 0x01;
78
79
    /**
80
     * @var array Mutual types.
81
     */
82
    public static $mutualTypes = [
83
        0x00 => 'Normal',
84
        0x01 => 'Suspend',
85
    ];
86
87
    /**
88
     * @var string the attribute name of which determines the `favorite` field.
89
     */
90
    public $favoriteAttribute = 'favorite';
91
92
    /**
93
     * Permit to build self relation.
94
     * @var boolean 
95
     */
96
    public $relationSelf = false;
97
98
    /**
99
     * Get whether this relation is favorite or not.
100
     * @return boolean
101
     */
102 1
    public function getIsFavorite()
103
    {
104 1
        $favoriteAttribute = $this->favoriteAttribute;
105 1
        return is_string($favoriteAttribute) ? (int) $this->$favoriteAttribute > 0 : null;
106
    }
107
108
    /**
109
     * Set favorite.
110
     * @param boolean $fav
111
     */
112 1
    public function setIsFavorite($fav)
113
    {
114 1
        $favoriteAttribute = $this->favoriteAttribute;
115 1
        return is_string($favoriteAttribute) ? $this->$favoriteAttribute = ($fav ? 1 : 0) : null;
116
    }
117
118
    /**
119
     * @inheritdoc
120
     */
121 8
    public function rules()
122
    {
123 8
        return array_merge(parent::rules(), $this->getUserRelationRules());
124
    }
125
126
    /**
127
     * Validation rules associated with user relation.
128
     * @return array rules.
129
     */
130 8
    public function getUserRelationRules()
131
    {
132 8
        $rules = [];
133 8
        if ($this->relationType == static::$relationMutual) {
134
            $rules = [
135 7
                [[$this->mutualTypeAttribute], 'in', 'range' => array_keys(static::$mutualTypes)],
136 7
                [[$this->mutualTypeAttribute], 'default', 'value' => static::$mutualTypeNormal],
137 7
            ];
138 7
        }
139 8
        return array_merge($rules, $this->getRemarkRules(), $this->getFavoriteRules(), $this->getGroupsRules(), $this->getOtherGuidRules());
0 ignored issues
show
Bug introduced by
It seems like getGroupsRules() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
140
    }
141
142
    /**
143
     * Get remark.
144
     * @return string remark.
145
     */
146
    public function getRemark()
147
    {
148
        $remarkAttribute = $this->remarkAttribute;
149
        return is_string($remarkAttribute) ? $this->$remarkAttribute : null;
150
    }
151
152
    /**
153
     * Set remark.
154
     * @param string $remark
155
     * @return string remark.
156
     */
157
    public function setRemark($remark)
158
    {
159
        $remarkAttribute = $this->remarkAttribute;
160
        return is_string($remarkAttribute) ? $this->$remarkAttribute = $remark : null;
161
    }
162
163
    /**
164
     * Validation rules associated with remark attribute.
165
     * @return array rules.
166
     */
167 8
    public function getRemarkRules()
168
    {
169 8
        return is_string($this->remarkAttribute) ? [
170 8
            [[$this->remarkAttribute], 'string'],
171 8
            [[$this->remarkAttribute], 'default', 'value' => ''],
172 8
            ] : [];
173
    }
174
175
    /**
176
     * Validation rules associated with favorites attribute.
177
     * @return array rules.
178
     */
179 8
    public function getFavoriteRules()
180
    {
181 8
        return is_string($this->favoriteAttribute) ? [
182 8
            [[$this->favoriteAttribute], 'boolean'],
183 8
            [[$this->favoriteAttribute], 'default', 'value' => 0],
184 8
            ] : [];
185
    }
186
187
    /**
188
     * Validation rules associated with other guid attribute.
189
     * @return array rules.
190
     */
191 8
    public function getOtherGuidRules()
192
    {
193
        $rules = [
194 8
            [[$this->otherGuidAttribute], 'required'],
195 8
            [[$this->otherGuidAttribute], 'string', 'max' => 36],
196 8
            [[$this->otherGuidAttribute, $this->createdByAttribute], 'unique', 'targetAttribute' => [$this->otherGuidAttribute, $this->createdByAttribute]],
0 ignored issues
show
Bug introduced by
The property createdByAttribute does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
197 8
        ];
198 8
        return $rules;
199
    }
200
201
    /**
202
     * Attach events associated with user relation.
203
     */
204 8
    public function initUserRelationEvents()
205
    {
206 8
        $this->on(static::EVENT_INIT, [$this, 'onInitBlamesLimit']);
0 ignored issues
show
Bug introduced by
It seems like on() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
207 8
        $this->on(static::$eventNewRecordCreated, [$this, 'onInitGroups']);
0 ignored issues
show
Bug introduced by
It seems like on() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
208 8
        $this->on(static::$eventNewRecordCreated, [$this, 'onInitRemark']);
0 ignored issues
show
Bug introduced by
It seems like on() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
209 8
        $this->on(static::$eventMultipleBlamesChanged, [$this, 'onBlamesChanged']);
0 ignored issues
show
Bug introduced by
It seems like on() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
210 8
        $this->on(static::EVENT_AFTER_INSERT, [$this, 'onInsertRelation']);
0 ignored issues
show
Bug introduced by
It seems like on() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
211 8
        $this->on(static::EVENT_AFTER_UPDATE, [$this, 'onUpdateRelation']);
0 ignored issues
show
Bug introduced by
It seems like on() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
212 8
        $this->on(static::EVENT_AFTER_DELETE, [$this, 'onDeleteRelation']);
0 ignored issues
show
Bug introduced by
It seems like on() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
213 8
    }
214
215
    /**
216
     * Get opposite relation to self.
217
     * @return \vistart\Models\models\BaseUserRelationModel
218
     */
219 7
    public function getOpposite()
220
    {
221 7
        if ($this->isNewRecord) {
0 ignored issues
show
Bug introduced by
The property isNewRecord does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
222 1
            return null;
223
        }
224 7
        $createdByAttribute = $this->createdByAttribute;
225 7
        $otherGuidAttribute = $this->otherGuidAttribute;
226 7
        return static::find()->opposite($this->$createdByAttribute, $this->$otherGuidAttribute);
227
    }
228
229
    /**
230
     * Build a suspend mutual relation, not support single relation.
231
     * @param BaseUserModel|string $user Initiator or its GUID.
232
     * @param BaseUserModel|string $other Recipient or its GUID.
233
     * @return \vistart\Models\models\BaseUserRelationModel The relation will be
234
     * given if exists, or return a new relation.
235
     */
236 1
    public static function buildSuspendRelation($user, $other)
237
    {
238 1
        $relation = static::buildRelation($user, $other);
239 1
        $btAttribute = $relation->mutualTypeAttribute;
240 1
        $relation->$btAttribute = static::$mutualTypeSuspend;
241 1
        return $relation;
242
    }
243
244
    /**
245
     * Build a normal relation.
246
     * @param BaseUserModel|string $user Initiator or its GUID.
247
     * @param BaseUserModel|string $other Recipient or its GUID.
248
     * @return \vistart\Models\models\BaseUserRelationModel The relation will be
249
     * given if exists, or return a new relation.
250
     */
251 8
    public static function buildNormalRelation($user, $other)
252
    {
253 8
        $relation = static::buildRelation($user, $other);
254 8
        if ($relation->relationType == static::$relationMutual) {
255 7
            $btAttribute = $relation->mutualTypeAttribute;
256 7
            $relation->$btAttribute = static::$mutualTypeNormal;
257 7
        }
258 8
        return $relation;
259
    }
260
261
    /**
262
     * Build relation between initiator and recipient.
263
     * @param BaseUserModel|string $user Initiator or its GUID.
264
     * @param BaseUserModel|string $other Recipient or its GUID.
265
     * @return \vistart\Models\models\BaseUserRelationModel The relation will be
266
     * given if exists, or return a new relation. Or return null if not allowed
267
     * to build self relation,
268
     */
269 8
    protected static function buildRelation($user, $other)
270
    {
271 8
        $relationQuery = static::find()->initiators($user)->recipients($other);
272 8
        $noInit = $relationQuery->noInitModel;
273 8
        $relation = $relationQuery->one();
274 8
        if (!$relation) {
275 8
            $createdByAttribute = $noInit->createdByAttribute;
276 8
            $otherGuidAttribute = $noInit->otherGuidAttribute;
277 8
            $userClass = $noInit->userClass;
278 8
            if ($user instanceof BaseUserModel) {
279 8
                $userClass = $userClass ? : $user->className();
280 8
                $user = $user->guid;
281 8
            }
282 8
            if ($other instanceof BaseUserModel) {
283 8
                $other = $other->guid;
284 8
            }
285 8
            if (!$noInit->relationSelf && $user == $other) {
286
                return null;
287
            }
288 8
            $relation = new static([$createdByAttribute => $user, $otherGuidAttribute => $other, 'userClass' => $userClass]);
0 ignored issues
show
Unused Code introduced by
The call to UserRelationTrait::__construct() has too many arguments starting with array($createdByAttribut...erClass' => $userClass).

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
289 8
        }
290 8
        return $relation;
291
    }
292
293
    /**
294
     * Build opposite relation throughout the current relation. The opposite
295
     * relation will be given if existed.
296
     * @param \vistart\Models\models\BaseUserRelationModel $relation
297
     * @return \vistart\Models\models\BaseUserRelationModel
298
     */
299 7
    protected static function buildOppositeRelation($relation)
300
    {
301 7
        if (!$relation) {
302
            return null;
303
        }
304 7
        $createdByAttribute = $relation->createdByAttribute;
305 7
        $otherGuidAttribute = $relation->otherGuidAttribute;
306 7
        $opposite = static::buildRelation($relation->$otherGuidAttribute, $relation->$createdByAttribute);
307 7
        if ($relation->relationType == static::$relationSingle) {
308
            $opposite->relationType = static::$relationSingle;
309 7
        } elseif ($relation->relationType == static::$relationMutual) {
310 7
            $mutualTypeAttribute = $relation->mutualTypeAttribute;
311 7
            $opposite->$mutualTypeAttribute = $relation->$mutualTypeAttribute;
312 7
        }
313 7
        return $opposite;
314
    }
315
316
    /**
317
     * Remove myself.
318
     * @return integer|false The number of relations removed, or false if the remove
319
     * is unsuccessful for some reason. Note that it is possible the number of relations
320
     * removed is 0, even though the remove execution is successful.
321
     */
322 2
    public function remove()
323
    {
324 2
        return $this->delete();
0 ignored issues
show
Bug introduced by
The method delete() does not exist on vistart\Models\traits\UserRelationTrait. Did you maybe mean onDeleteRelation()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
325
    }
326
327
    /**
328
     * Remove first relation between initiator(s) and recipient(s).
329
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
330
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
331
     * @return integer|false The number of relations removed.
332
     */
333 1
    public static function removeOneRelation($user, $other)
334
    {
335 1
        return static::find()->initiators($user)->recipients($other)->one()->delete();
336
    }
337
338
    /**
339
     * Remove all relations between initiator(s) and recipient(s).
340
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
341
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
342
     * @return integer The number of relations removed.
343
     */
344 2
    public static function removeAllRelations($user, $other)
345
    {
346 2
        $rni = static::buildNoInitModel();
347 2
        $createdByAttribute = $rni->createdByAttribute;
348 2
        $otherGuidAttribute = $rni->otherGuidAttribute;
349 2
        return static::deleteAll([$createdByAttribute => $user, $otherGuidAttribute => $other]);
350
    }
351
352
    /**
353
     * Get first relation between initiator(s) and recipient(s).
354
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
355
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
356
     * @return \vistart\Models\models\BaseUserRelationModel
357
     */
358 1
    public static function findOneRelation($user, $other)
359
    {
360 1
        return static::find()->initiators($user)->recipients($other)->one();
361
    }
362
363
    /**
364
     * Get first opposite relation between initiator(s) and recipient(s).
365
     * @param BaseUserModel|string $user Initiator or its guid, or array of them.
366
     * @param BaseUserModel|string $other Recipient or its guid, or array of them.
367
     * @return \vistart\Models\models\BaseUserRelationModel
368
     */
369 7
    public static function findOneOppositeRelation($user, $other)
370
    {
371 7
        return static::find()->initiators($other)->recipients($user)->one();
372
    }
373
374
    /**
375
     * Get user's or users' all relations, or by specified groups.
376
     * @param BaseUserModel|string|array $user Initiator or its GUID, or Initiators or their GUIDs.
377
     * @param BaseUserRelationGroupModel|string|array|null $groups UserRelationGroup or its guid, or array of them. If you do not want to delimit the groups, please assign null.
378
     * @return array all eligible relations
379
     */
380
    public static function findOnesAllRelations($user, $groups = null)
381
    {
382
        return static::find()->initiators($user)->groups($groups)->all();
383
    }
384
385
    /**
386
     * Initialize groups attribute.
387
     * @param \yii\base\Event $event
388
     */
389 8
    public function onInitGroups($event)
390
    {
391 8
        $sender = $event->sender;
392 8
        $sender->removeAllGroups();
393 8
    }
394
395
    /**
396
     * Initialize remark attribute.
397
     * @param \yii\base\Event $event
398
     */
399 8
    public function onInitRemark($event)
400
    {
401 8
        $sender = $event->sender;
402 8
        $remarkAttribute = $sender->remarkAttribute;
403 8
        is_string($remarkAttribute) ? $sender->$remarkAttribute = '' : null;
404 8
    }
405
406
    /**
407
     * The event triggered after insert new relation.
408
     * The opposite relation should be inserted without triggering events
409
     * simultaneously after new relation inserted,
410
     * @param \yii\base\Event $event
411
     */
412 8
    public function onInsertRelation($event)
413
    {
414 8
        $sender = $event->sender;
415 8
        if ($sender->relationType == static::$relationMutual) {
416 7
            $opposite = static::buildOppositeRelation($sender);
417 7
            $opposite->off(static::EVENT_AFTER_INSERT, [$opposite, 'onInsertRelation']);
418 7
            if (!$opposite->save()) {
419
                $opposite->recordWarnings();
420
            }
421 7
            $opposite->on(static::EVENT_AFTER_INSERT, [$opposite, 'onInsertRelation']);
422 7
        }
423 8
    }
424
425
    /**
426
     * The event triggered after update relation.
427
     * The opposite relation should be updated without triggering events
428
     * simultaneously after existed relation removed.
429
     * @param \yii\base\Event $event
430
     */
431 3
    public function onUpdateRelation($event)
432
    {
433 3
        $sender = $event->sender;
434 3
        if ($sender->relationType == static::$relationMutual) {
435 3
            $opposite = static::buildOppositeRelation($sender);
436 3
            $opposite->off(static::EVENT_AFTER_UPDATE, [$opposite, 'onUpdateRelation']);
437 3
            if (!$opposite->save()) {
438
                $opposite->recordWarnings();
439
            }
440 3
            $opposite->on(static::EVENT_AFTER_UPDATE, [$opposite, 'onUpdateRelation']);
441 3
        }
442 3
    }
443
444
    /**
445
     * The event triggered after delete relation.
446
     * The opposite relation should be deleted without triggering events
447
     * simultaneously after existed relation removed.
448
     * @param \yii\base\Event $event
449
     */
450 2
    public function onDeleteRelation($event)
451
    {
452 2
        $sender = $event->sender;
453 2
        if ($sender->relationType == static::$relationMutual) {
454 2
            $createdByAttribute = $sender->createdByAttribute;
455 2
            $otherGuidAttribute = $sender->otherGuidAttribute;
456 2
            $sender->off(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
457 2
            static::removeAllRelations($sender->$otherGuidAttribute, $sender->$createdByAttribute);
458 2
            $sender->on(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
459 2
        }
460 2
    }
461
}
462