Completed
Push — master ( 113cf9...315017 )
by vistart
05:37
created

UserRelationTrait   C

Complexity

Total Complexity 74

Size/Duplication

Total Lines 535
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 67.23%

Importance

Changes 4
Bugs 1 Features 2
Metric Value
wmc 74
lcom 1
cbo 10
dl 0
loc 535
ccs 119
cts 177
cp 0.6723
rs 5.5244
c 4
b 1
f 2

31 Methods

Rating   Name   Duplication   Size   Complexity  
A getIsFavorite() 0 5 3
A setIsFavorite() 0 5 4
A rules() 0 4 1
A getUserRelationRules() 0 11 2
A getRemark() 0 5 2
A setRemark() 0 5 2
A getRemarkRules() 0 7 2
A getFavoriteRules() 0 7 2
A getOtherGuidRules() 0 7 1
A initUserRelationEvents() 0 10 1
A getOpposite() 0 7 2
A isFollowed() 0 4 1
A isFollowing() 0 4 1
A isMutual() 0 4 2
A isFriend() 0 15 4
A buildSuspendRelation() 0 10 3
A buildNormalRelation() 0 12 3
C buildRelation() 0 23 7
A buildOppositeRelation() 0 16 4
D insertRelation() 0 27 10
A remove() 0 4 1
A removeOneRelation() 0 4 1
A removeAllRelations() 0 7 1
A findOneRelation() 0 4 1
A findOneOppositeRelation() 0 4 1
A findOnesAllRelations() 0 4 1
A onInitGroups() 0 5 1
A onInitRemark() 0 6 2
A onInsertRelation() 0 13 3
A onUpdateRelation() 0 13 3
A onDeleteRelation() 0 11 2

How to fix   Complexity   

Complex Class

Complex classes like UserRelationTrait often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UserRelationTrait, and based on these observations, apply Extract Interface, too.

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\base\models\traits;
14
15
use rhosocial\base\models\models\BaseUserModel;
16
use rhosocial\base\models\traits\MultipleBlameableTrait as mb;
17
use yii\base\ModelEvent;
18
use yii\base\InvalidConfigException;
19
use yii\base\InvalidValueException;
20
use yii\db\Connection;
21
use yii\db\IntegrityException;
22
23
/**
24
 * Relation features.
25
 * This trait should be used in user relation model which is extended from
26
 * [[BaseBlameableModel]], and is specified `$userClass` property. And the user
27
 * class should be extended from [[BaseUserModel]], or any other classes used
28
 * [[UserTrait]].
29
 * Notice: Several methods associated with "inserting", "updating" and "removing" may
30
 * involve more DB operations, I strongly recommend those methods to be placed in
31
 * transaction execution, in order to ensure data consistency.
32
 * If you want to use group feature, the class used [[UserRelationGroupTrait]]
33
 * must be used coordinately.
34
 * @property array $groupGuids the guid array of all groups which owned by current relation.
35
 * @property-read array $favoriteRules
36
 * @property boolean $isFavorite
37
 * @property-read static $opposite
38
 * @property-read array $otherGuidRules
39
 * @property string $remark
40
 * @property-read array $remarkRules
41
 * @property-read array $userRelationRules
42
 * @property-read mixed $group
43
 * @property-read array $groupMembers
44
 * @property array $groupGuids
45
 * @property-read array $allGroups
46
 * @property-read array $nonGroupMembers
47
 * @property-read integer $groupsCount
48
 * @property-read array $groupsRules
49
 * @version 1.0
50
 * @author vistart <[email protected]>
51
 */
52
trait UserRelationTrait
53
{
54
    use mb,
55
        MutualTrait {
56
        mb::addBlame as addGroup;
57
        mb::createBlame as createGroup;
58
        mb::addOrCreateBlame as addOrCreateGroup;
59
        mb::removeBlame as removeGroup;
60
        mb::removeAllBlames as removeAllGroups;
61
        mb::getBlame as getGroup;
62
        mb::getOrCreateBlame as getOrCreateGroup;
63
        mb::getBlameds as getGroupMembers;
64
        mb::getBlameGuids as getGroupGuids;
65
        mb::setBlameGuids as setGroupGuids;
66
        mb::getAllBlames as getAllGroups;
67
        mb::getNonBlameds as getNonGroupMembers;
68
        mb::getBlamesCount as getGroupsCount;
69
        mb::getMultipleBlameableAttributeRules as getGroupsRules;
70
    }
71
72
    /**
73
     * @var string
74
     */
75
    public $remarkAttribute = 'remark';
76
    public static $relationSingle = 0;
77
    public static $relationMutual = 1;
78
    public $relationType = 1;
79
    public $relationTypes = [
80
        0 => 'Single',
81
        1 => 'Mutual',
82
    ];
83
84
    /**
85
     * @var string the attribute name of which determines the relation type.
86
     */
87
    public $mutualTypeAttribute = 'type';
88
    public static $mutualTypeNormal = 0x00;
89
    public static $mutualTypeSuspend = 0x01;
90
91
    /**
92
     * @var array Mutual types.
93
     */
94
    public static $mutualTypes = [
95
        0x00 => 'Normal',
96
        0x01 => 'Suspend',
97
    ];
98
99
    /**
100
     * @var string the attribute name of which determines the `favorite` field.
101
     */
102
    public $favoriteAttribute = 'favorite';
103
104
    /**
105
     * Permit to build self relation.
106
     * @var boolean 
107
     */
108
    public $relationSelf = false;
109
110
    /**
111
     * Get whether this relation is favorite or not.
112
     * @return boolean
113
     */
114 1
    public function getIsFavorite()
115
    {
116 1
        $favoriteAttribute = $this->favoriteAttribute;
117 1
        return (is_string($favoriteAttribute) && !empty($favoriteAttribute)) ? (int) $this->$favoriteAttribute > 0 : null;
118
    }
119
120
    /**
121
     * Set favorite.
122
     * @param boolean $fav
123
     */
124 1
    public function setIsFavorite($fav)
125
    {
126 1
        $favoriteAttribute = $this->favoriteAttribute;
127 1
        return (is_string($favoriteAttribute) && !empty($favoriteAttribute)) ? $this->$favoriteAttribute = ($fav ? 1 : 0) : null;
128
    }
129
130
    /**
131
     * @inheritdoc
132
     */
133 18
    public function rules()
134
    {
135 18
        return array_merge(parent::rules(), $this->getUserRelationRules());
136
    }
137
138
    /**
139
     * Validation rules associated with user relation.
140
     * @return array rules.
141
     */
142 18
    public function getUserRelationRules()
143
    {
144 18
        $rules = [];
145 18
        if ($this->relationType == static::$relationMutual) {
146
            $rules = [
147
                [[$this->mutualTypeAttribute], 'in', 'range' => array_keys(static::$mutualTypes)],
148
                [[$this->mutualTypeAttribute], 'default', 'value' => static::$mutualTypeNormal],
149
            ];
150
        }
151 18
        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...
152
    }
153
154
    /**
155
     * Get remark.
156
     * @return string remark.
157
     */
158 1
    public function getRemark()
159
    {
160 1
        $remarkAttribute = $this->remarkAttribute;
161 1
        return is_string($remarkAttribute) ? $this->$remarkAttribute : null;
162
    }
163
164
    /**
165
     * Set remark.
166
     * @param string $remark
167
     * @return string remark.
168
     */
169 1
    public function setRemark($remark)
170
    {
171 1
        $remarkAttribute = $this->remarkAttribute;
172 1
        return is_string($remarkAttribute) ? $this->$remarkAttribute = $remark : null;
173
    }
174
175
    /**
176
     * Validation rules associated with remark attribute.
177
     * @return array rules.
178
     */
179 18
    public function getRemarkRules()
180
    {
181 18
        return is_string($this->remarkAttribute) ? [
182 18
            [[$this->remarkAttribute], 'string'],
183 18
            [[$this->remarkAttribute], 'default', 'value' => ''],
184 18
            ] : [];
185
    }
186
187
    /**
188
     * Validation rules associated with favorites attribute.
189
     * @return array rules.
190
     */
191 18
    public function getFavoriteRules()
192
    {
193 18
        return is_string($this->favoriteAttribute) ? [
194 18
            [[$this->favoriteAttribute], 'boolean'],
195 18
            [[$this->favoriteAttribute], 'default', 'value' => 0],
196 18
            ] : [];
197
    }
198
199
    /**
200
     * Validation rules associated with other guid attribute.
201
     * @return array rules.
202
     */
203 18
    public function getOtherGuidRules()
204
    {
205 18
        $rules = array_merge($this->getMutualRules(), [
206 18
            [[$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...
207
        ]);
208 18
        return $rules;
209
    }
210
211
    /**
212
     * Attach events associated with user relation.
213
     */
214 19
    public function initUserRelationEvents()
215
    {
216 19
        $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...
217 19
        $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...
218 19
        $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...
219 19
        $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...
220 19
        $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...
221 19
        $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...
222 19
        $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...
223 19
    }
224
225
    /**
226
     * Get opposite relation against self.
227
     * @return static
228
     */
229 1
    public function getOpposite()
230
    {
231 1
        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...
232 1
            return null;
233
        }
234 1
        return static::find()->opposite($this->initiator, $this->recipient);
235
    }
236
237
    /**
238
     * Check whether the initiator is followed by recipient.
239
     * @param BaseUserModel $initiator
240
     * @param BaseUserModel $recipient
241
     * @return boolean
242
     */
243 4
    public static function isFollowed($initiator, $recipient)
244
    {
245 4
        return static::find()->initiators($recipient)->recipients($initiator)->exists();
246
    }
247
248
    /**
249
     * Check whether the initiator is following recipient.
250
     * @param BaseUserModel $initiator
251
     * @param BaseUserModel $recipient
252
     * @return boolean
253
     */
254 4
    public static function isFollowing($initiator, $recipient)
255
    {
256 4
        return static::find()->initiators($initiator)->recipients($recipient)->exists();
257
    }
258
259
    /**
260
     * Check whether the initiator is following and followed by recipient mutually (Single Relation).
261
     * Or check whether the initiator and recipient are friend whatever the mutual type is normal or suspend.
262
     * @param BaseUserModel $initiator
263
     * @param BaseUserModel $recipient
264
     * @return boolean
265
     */
266 3
    public static function isMutual($initiator, $recipient)
267
    {
268 3
        return static::isFollowed($initiator, $recipient) && static::isFollowing($initiator, $recipient);
269
    }
270
271
    /**
272
     * Check whether the initiator is following and followed by recipient mutually (Single Relation).
273
     * Or check whether the initiator and recipient are friend if the mutual type is normal.
274
     * @param BaseUserModel $initiator
275
     * @param BaseUserModel $recipient
276
     * @return boolean
277
     */
278 2
    public static function isFriend($initiator, $recipient)
279
    {
280 2
        $query = static::find();
281 2
        $model = $query->noInitModel;
282
        /* @var $model static */
283 2
        if ($model->relationType == static::$relationSingle) {
284 2
            return static::isMutual($initiator, $recipient);
285
        }
286
        if ($model->relationType == static::$relationMutual) {
287
            $relation = static::find()->initiators($initiator)->recipients($recipient)->andWhere([$model->mutualTypeAttribute => static::$mutualTypeNormal])->exists();
288
            $inverse = static::find()->recipients($initiator)->initiators($recipient)->andWhere([$model->mutualTypeAttribute => static::$mutualTypeNormal])->exists();
289
            return $relation && $inverse;
290
        }
291
        return false;
292
    }
293
294
    /**
295
     * Build new or return existed suspend mutual relation, or return null if
296
     * current type is not mutual.
297
     * @see buildRelation()
298
     * @param BaseUserModel|string $user Initiator or its GUID.
299
     * @param BaseUserModel|string $other Recipient or its GUID.
300
     * @return static The relation will be
301
     * given if exists, or return a new relation.
302
     */
303 1
    public static function buildSuspendRelation($user, $other)
304
    {
305 1
        $relation = static::buildRelation($user, $other);
306 1
        if (!$relation || $relation->relationType != static::$relationMutual) {
307 1
            return null;
308
        }
309
        $btAttribute = $relation->mutualTypeAttribute;
310
        $relation->$btAttribute = static::$mutualTypeSuspend;
311
        return $relation;
312
    }
313
314
    /**
315
     * Build new or return existed normal relation.
316
     * The status of mutual relation will be changed to normal if it is not. 
317
     * @see buildRelation()
318
     * @param BaseUserModel|string $user Initiator or its GUID.
319
     * @param BaseUserModel|string $other Recipient or its GUID.
320
     * @return static The relation will be
321
     * given if exists, or return a new relation.
322
     */
323 19
    public static function buildNormalRelation($user, $other)
324
    {
325 19
        $relation = static::buildRelation($user, $other);
326 19
        if (!$relation) {
327 1
            return null;
328
        }
329 19
        if ($relation->relationType == static::$relationMutual) {
330
            $btAttribute = $relation->mutualTypeAttribute;
331
            $relation->$btAttribute = static::$mutualTypeNormal;
332
        }
333 19
        return $relation;
334
    }
335
336
    /**
337
     * Build new or return existed relation between initiator and recipient.
338
     * If relation between initiator and recipient is not found, new relation will
339
     * be built. If initiator and recipient are the same one and it is not allowed
340
     * to build self relation, null will be given.
341
     * If you want to know whether the relation exists, you can check the return
342
     * value of `getIsNewRecord()` method.
343
     * @param BaseUserModel|string $user Initiator or its GUID.
344
     * @param BaseUserModel|string $other Recipient or its GUID.
345
     * @return static The relation will be
346
     * given if exists, or return a new relation. Or return null if not allowed
347
     * to build self relation,
348
     */
349 19
    protected static function buildRelation($user, $other)
350
    {
351 19
        $relationQuery = static::find()->initiators($user)->recipients($other);
352 19
        $noInit = $relationQuery->noInitModel;
353 19
        $relation = $relationQuery->one();
354 19
        if (!$relation) {
355 19
            $createdByAttribute = $noInit->createdByAttribute;
356 19
            $otherGuidAttribute = $noInit->otherGuidAttribute;
357 19
            $userClass = $noInit->userClass;
358 19
            if ($user instanceof BaseUserModel) {
359 19
                $userClass = $userClass ? : $user->className();
360 19
                $user = $user->getGUID();
361
            }
362 19
            if ($other instanceof BaseUserModel) {
363 19
                $other = $other->getGUID();
364
            }
365 19
            if (!$noInit->relationSelf && $user == $other) {
366 1
                return null;
367
            }
368 19
            $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...
369
        }
370 19
        return $relation;
371
    }
372
373
    /**
374
     * Build opposite relation throughout the current relation. The opposite
375
     * relation will be given if existed.
376
     * @param static $relation
0 ignored issues
show
introduced by
The type UserRelationTrait for parameter $relation is a trait, and thus cannot be used for type-hinting in PHP. Maybe consider adding an interface and use that for type-hinting?
Loading history...
377
     * @return static
378
     */
379
    protected static function buildOppositeRelation($relation)
380
    {
381
        if (!$relation) {
382
            return null;
383
        }
384
        $createdByAttribute = $relation->createdByAttribute;
385
        $otherGuidAttribute = $relation->otherGuidAttribute;
386
        $opposite = static::buildRelation($relation->$otherGuidAttribute, $relation->$createdByAttribute);
387
        if ($relation->relationType == static::$relationSingle) {
388
            $opposite->relationType = static::$relationSingle;
389
        } elseif ($relation->relationType == static::$relationMutual) {
390
            $mutualTypeAttribute = $relation->mutualTypeAttribute;
391
            $opposite->$mutualTypeAttribute = $relation->$mutualTypeAttribute;
392
        }
393
        return $opposite;
394
    }
395
    
396
    /**
397
     * Insert relation, the process is placed in a transaction.
398
     * Note: This feature only support relational databases and skip all errors.
399
     * If you don't want to use transaction or database doesn't support it,
400
     * please use `save()` directly.
401
     * @param static $relation
0 ignored issues
show
introduced by
The type UserRelationTrait for parameter $relation is a trait, and thus cannot be used for type-hinting in PHP. Maybe consider adding an interface and use that for type-hinting?
Loading history...
402
     * @param Connection $db
403
     * @return boolean
404
     * @throws InvalidValueException
405
     * @throws InvalidConfigException
406
     * @throws IntegrityException
407
     */
408
    public static function insertRelation($relation, Connection $db = null)
409
    {
410
        if (!$relation || !($relation instanceof static)) {
411
            return false;
412
        }
413
        if (!$relation->getIsNewRecord()) {
0 ignored issues
show
Bug introduced by
It seems like getIsNewRecord() 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...
414
            throw new InvalidValueException('This relation is not new one.');
415
        }
416
        if (!$db && isset(\Yii::$app->db) && \Yii::$ap->db instanceof Connection) {
417
            $db = \Yii::$app->db;
418
        }
419
        if (!$db) {
420
            throw new InvalidConfigException('Invalid database connection.');
421
        }
422
        /* @var $db Connection */
423
        $transaction = $db->beginTransaction();
424
        try {
425
            if (!$relation->save()) {
0 ignored issues
show
Bug introduced by
It seems like save() 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...
426
                throw new IntegrityException('Relation insert failed.');
427
            }
428
            $transaction->commit();
429
        } catch (\Exception $ex) {
430
            $transaction->rollBack();
431
            return false;
432
        }
433
        return true;
434
    }
435
436
    /**
437
     * Remove myself.
438
     * @return integer|false The number of relations removed, or false if the remove
439
     * is unsuccessful for some reason. Note that it is possible the number of relations
440
     * removed is 0, even though the remove execution is successful.
441
     */
442 19
    public function remove()
443
    {
444 19
        return $this->delete();
0 ignored issues
show
Bug introduced by
The method delete() does not exist on rhosocial\base\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...
445
    }
446
447
    /**
448
     * Remove first relation between initiator(s) and recipient(s).
449
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
450
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
451
     * @return integer|false The number of relations removed.
452
     */
453 1
    public static function removeOneRelation($user, $other)
454
    {
455 1
        return static::find()->initiators($user)->recipients($other)->one()->remove();
456
    }
457
458
    /**
459
     * Remove all relations between initiator(s) and recipient(s).
460
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
461
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
462
     * @return integer The number of relations removed.
463
     */
464 1
    public static function removeAllRelations($user, $other)
465
    {
466 1
        $rni = static::buildNoInitModel();
467 1
        $createdByAttribute = $rni->createdByAttribute;
468 1
        $otherGuidAttribute = $rni->otherGuidAttribute;
469 1
        return static::deleteAll([$createdByAttribute => $user, $otherGuidAttribute => $other]);
470
    }
471
472
    /**
473
     * Get first relation between initiator(s) and recipient(s).
474
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
475
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
476
     * @return static
477
     */
478 4
    public static function findOneRelation($user, $other)
479
    {
480 4
        return static::find()->initiators($user)->recipients($other)->one();
481
    }
482
483
    /**
484
     * Get first opposite relation between initiator(s) and recipient(s).
485
     * @param BaseUserModel|string $user Initiator or its guid, or array of them.
486
     * @param BaseUserModel|string $other Recipient or its guid, or array of them.
487
     * @return static
488
     */
489 1
    public static function findOneOppositeRelation($user, $other)
490
    {
491 1
        return static::find()->initiators($other)->recipients($user)->one();
492
    }
493
494
    /**
495
     * Get user's or users' all relations, or by specified groups.
496
     * @param BaseUserModel|string|array $user Initiator or its GUID, or Initiators or their GUIDs.
497
     * @param BaseUserRelationGroupModel|string|array|null $groups UserRelationGroup
498
     * or its guid, or array of them. If you do not want to delimit the groups, please assign null.
499
     * @return array all eligible relations
500
     */
501 1
    public static function findOnesAllRelations($user, $groups = null)
502
    {
503 1
        return static::find()->initiators($user)->groups($groups)->all();
504
    }
505
506
    /**
507
     * Initialize groups attribute.
508
     * @param ModelEvent $event
509
     */
510 19
    public function onInitGroups($event)
511
    {
512 19
        $sender = $event->sender;
513 19
        $sender->removeAllGroups();
514 19
    }
515
516
    /**
517
     * Initialize remark attribute.
518
     * @param ModelEvent $event
519
     */
520 19
    public function onInitRemark($event)
521
    {
522 19
        $sender = $event->sender;
523 19
        $remarkAttribute = $sender->remarkAttribute;
524 19
        is_string($remarkAttribute) ? $sender->$remarkAttribute = '' : null;
525 19
    }
526
527
    /**
528
     * The event triggered after insert new relation.
529
     * The opposite relation should be inserted without triggering events
530
     * simultaneously after new relation inserted,
531
     * @param ModelEvent $event
532
     * @throws IntegrityException throw if insert failed.
533
     */
534 18
    public function onInsertRelation($event)
535
    {
536 18
        $sender = $event->sender;
537 18
        if ($sender->relationType == static::$relationMutual) {
538
            $opposite = static::buildOppositeRelation($sender);
539
            $opposite->off(static::EVENT_AFTER_INSERT, [$opposite, 'onInsertRelation']);
0 ignored issues
show
Bug introduced by
It seems like off() 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...
540
            if (!$opposite->save()) {
0 ignored issues
show
Bug introduced by
It seems like save() 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...
541
                $opposite->recordWarnings();
0 ignored issues
show
Bug introduced by
It seems like recordWarnings() 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...
542
                throw new IntegrityException('Reverse relation insert failed.');
543
            }
544
            $opposite->on(static::EVENT_AFTER_INSERT, [$opposite, '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...
545
        }
546 18
    }
547
548
    /**
549
     * The event triggered after update relation.
550
     * The opposite relation should be updated without triggering events
551
     * simultaneously after existed relation removed.
552
     * @param ModelEvent $event
553
     * @throw IntegrityException throw if update failed.
554
     */
555 2
    public function onUpdateRelation($event)
556
    {
557 2
        $sender = $event->sender;
558 2
        if ($sender->relationType == static::$relationMutual) {
559
            $opposite = static::buildOppositeRelation($sender);
560
            $opposite->off(static::EVENT_AFTER_UPDATE, [$opposite, 'onUpdateRelation']);
0 ignored issues
show
Bug introduced by
It seems like off() 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...
561
            if (!$opposite->save()) {
0 ignored issues
show
Bug introduced by
It seems like save() 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...
562
                $opposite->recordWarnings();
0 ignored issues
show
Bug introduced by
It seems like recordWarnings() 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...
563
                throw new IntegrityException('Reverse relation update failed.');
564
            }
565
            $opposite->on(static::EVENT_AFTER_UPDATE, [$opposite, '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...
566
        }
567 2
    }
568
569
    /**
570
     * The event triggered after delete relation.
571
     * The opposite relation should be deleted without triggering events
572
     * simultaneously after existed relation removed.
573
     * @param ModelEvent $event
574
     */
575 19
    public function onDeleteRelation($event)
576
    {
577 19
        $sender = $event->sender;
578 19
        if ($sender->relationType == static::$relationMutual) {
579
            $createdByAttribute = $sender->createdByAttribute;
580
            $otherGuidAttribute = $sender->otherGuidAttribute;
581
            $sender->off(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
582
            static::removeAllRelations($sender->$otherGuidAttribute, $sender->$createdByAttribute);
583
            $sender->on(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
584
        }
585 19
    }
586
}
587