Completed
Push — master ( 13e074...5da848 )
by vistart
05:46
created

UserRelationTrait::findOneOppositeRelation()   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 2
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\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 19
    public function rules()
134
    {
135 19
        return array_merge(parent::rules(), $this->getUserRelationRules());
136
    }
137
138
    /**
139
     * Validation rules associated with user relation.
140
     * @return array rules.
141
     */
142 19
    public function getUserRelationRules()
143
    {
144 19
        $rules = [];
145 19
        if ($this->relationType == static::$relationMutual) {
146
            $rules = [
147 1
                [[$this->mutualTypeAttribute], 'in', 'range' => array_keys(static::$mutualTypes)],
148 1
                [[$this->mutualTypeAttribute], 'default', 'value' => static::$mutualTypeNormal],
149
            ];
150
        }
151 19
        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 19
    public function getRemarkRules()
180
    {
181 19
        return is_string($this->remarkAttribute) ? [
182 19
            [[$this->remarkAttribute], 'string'],
183 19
            [[$this->remarkAttribute], 'default', 'value' => ''],
184 19
            ] : [];
185
    }
186
187
    /**
188
     * Validation rules associated with favorites attribute.
189
     * @return array rules.
190
     */
191 19
    public function getFavoriteRules()
192
    {
193 19
        return is_string($this->favoriteAttribute) ? [
194 19
            [[$this->favoriteAttribute], 'boolean'],
195 19
            [[$this->favoriteAttribute], 'default', 'value' => 0],
196 19
            ] : [];
197
    }
198
199
    /**
200
     * Validation rules associated with other guid attribute.
201
     * @return array rules.
202
     */
203 19
    public function getOtherGuidRules()
204
    {
205 19
        $rules = array_merge($this->getMutualRules(), [
206 19
            [[$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 19
        return $rules;
209
    }
210
211
    /**
212
     * Attach events associated with user relation.
213
     */
214 20
    public function initUserRelationEvents()
215
    {
216 20
        $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 20
        $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 20
        $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 20
        $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 20
        $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 20
        $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 20
        $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 20
    }
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 2
    public static function buildSuspendRelation($user, $other)
304
    {
305 2
        $relation = static::buildRelation($user, $other);
306 2
        if (!$relation || $relation->relationType != static::$relationMutual) {
307 1
            return null;
308
        }
309 1
        $btAttribute = $relation->mutualTypeAttribute;
310 1
        $relation->$btAttribute = static::$mutualTypeSuspend;
311 1
        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 20
    public static function buildNormalRelation($user, $other)
324
    {
325 20
        $relation = static::buildRelation($user, $other);
326 20
        if (!$relation) {
327 1
            return null;
328
        }
329 20
        if ($relation->relationType == static::$relationMutual) {
330 1
            $btAttribute = $relation->mutualTypeAttribute;
331 1
            $relation->$btAttribute = static::$mutualTypeNormal;
332
        }
333 20
        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 20
    protected static function buildRelation($user, $other)
350
    {
351 20
        $relationQuery = static::find()->initiators($user)->recipients($other);
352 20
        $noInit = $relationQuery->noInitModel;
353 20
        $relation = $relationQuery->one();
354 20
        if (!$relation) {
355 20
            $createdByAttribute = $noInit->createdByAttribute;
356 20
            $otherGuidAttribute = $noInit->otherGuidAttribute;
357 20
            $userClass = $noInit->userClass;
358 20
            if ($user instanceof BaseUserModel) {
359 20
                $userClass = $userClass ? : $user->className();
360 20
                $user = $user->getGUID();
361
            }
362 20
            if ($other instanceof BaseUserModel) {
363 20
                $other = $other->getGUID();
364
            }
365 20
            if (!$noInit->relationSelf && $user == $other) {
366 1
                return null;
367
            }
368 20
            $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 20
        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 1
    protected static function buildOppositeRelation($relation)
380
    {
381 1
        if (!$relation) {
382
            return null;
383
        }
384 1
        $createdByAttribute = $relation->createdByAttribute;
385 1
        $otherGuidAttribute = $relation->otherGuidAttribute;
386 1
        $opposite = static::buildRelation($relation->$otherGuidAttribute, $relation->$createdByAttribute);
387 1
        if ($relation->relationType == static::$relationSingle) {
388
            $opposite->relationType = static::$relationSingle;
389 1
        } elseif ($relation->relationType == static::$relationMutual) {
390 1
            $mutualTypeAttribute = $relation->mutualTypeAttribute;
391 1
            $opposite->$mutualTypeAttribute = $relation->$mutualTypeAttribute;
392
        }
393 1
        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 20
    public function remove()
443
    {
444 20
        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 2
    public static function removeAllRelations($user, $other)
465
    {
466 2
        $rni = static::buildNoInitModel();
467 2
        $createdByAttribute = $rni->createdByAttribute;
468 2
        $otherGuidAttribute = $rni->otherGuidAttribute;
469 2
        return static::deleteAll([$createdByAttribute => BaseUserModel::compositeGUIDs($user), $otherGuidAttribute => BaseUserModel::compositeGUIDs($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 20
    public function onInitGroups($event)
511
    {
512 20
        $sender = $event->sender;
513 20
        $sender->removeAllGroups();
514 20
    }
515
516
    /**
517
     * Initialize remark attribute.
518
     * @param ModelEvent $event
519
     */
520 20
    public function onInitRemark($event)
521
    {
522 20
        $sender = $event->sender;
523 20
        $remarkAttribute = $sender->remarkAttribute;
524 20
        is_string($remarkAttribute) ? $sender->$remarkAttribute = '' : null;
525 20
    }
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 19
    public function onInsertRelation($event)
535
    {
536 19
        $sender = $event->sender;
537 19
        if ($sender->relationType == static::$relationMutual) {
538 1
            $opposite = static::buildOppositeRelation($sender);
539 1
            $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 1
            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 1
            $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 19
    }
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 20
    public function onDeleteRelation($event)
576
    {
577 20
        $sender = $event->sender;
578 20
        if ($sender->relationType == static::$relationMutual) {
579 1
            $createdByAttribute = $sender->createdByAttribute;
580 1
            $otherGuidAttribute = $sender->otherGuidAttribute;
581 1
            $sender->off(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
582 1
            static::removeAllRelations($sender->$otherGuidAttribute, $sender->$createdByAttribute);
583 1
            $sender->on(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
584
        }
585 20
    }
586
}
587