Completed
Push — master ( 88852e...d53907 )
by vistart
05:23
created

UserRelationTrait::getRecipient()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

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...
137
    }
138
139
    /**
140
     * Get recipient.
141
     * @return \vistart\Models\queries\BaseUserQuery
142
     */
143
    public function getRecipient()
144
    {
145
        if (!is_string($this->otherGuidAttribute)) {
146
            return null;
147
        }
148
        $userClass = $this->userClass;
0 ignored issues
show
Bug introduced by
The property userClass 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...
149
        $model = $userClass::buildNoInitModel();
150
        return $this->hasOne($userClass::className(), [$model->guidAttribute => $this->otherGuidAttribute]);
0 ignored issues
show
Bug introduced by
It seems like hasOne() 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...
151
    }
152
153
    /**
154
     * Validation rules associated with user relation.
155
     * @return array rules.
156
     */
157 8
    public function getUserRelationRules()
158
    {
159 8
        $rules = [];
160 8
        if ($this->relationType == static::$relationMutual) {
161
            $rules = [
162 7
                [[$this->mutualTypeAttribute], 'in', 'range' => array_keys(static::$mutualTypes)],
163 7
                [[$this->mutualTypeAttribute], 'default', 'value' => static::$mutualTypeNormal],
164 7
            ];
165 7
        }
166 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...
167
    }
168
169
    /**
170
     * Get remark.
171
     * @return string remark.
172
     */
173
    public function getRemark()
174
    {
175
        $remarkAttribute = $this->remarkAttribute;
176
        return is_string($remarkAttribute) ? $this->$remarkAttribute : null;
177
    }
178
179
    /**
180
     * Set remark.
181
     * @param string $remark
182
     * @return string remark.
183
     */
184
    public function setRemark($remark)
185
    {
186
        $remarkAttribute = $this->remarkAttribute;
187
        return is_string($remarkAttribute) ? $this->$remarkAttribute = $remark : null;
188
    }
189
190
    /**
191
     * Validation rules associated with remark attribute.
192
     * @return array rules.
193
     */
194 8
    public function getRemarkRules()
195
    {
196 8
        return is_string($this->remarkAttribute) ? [
197 8
            [[$this->remarkAttribute], 'string'],
198 8
            [[$this->remarkAttribute], 'default', 'value' => ''],
199 8
            ] : [];
200
    }
201
202
    /**
203
     * Validation rules associated with favorites attribute.
204
     * @return array rules.
205
     */
206 8
    public function getFavoriteRules()
207
    {
208 8
        return is_string($this->favoriteAttribute) ? [
209 8
            [[$this->favoriteAttribute], 'boolean'],
210 8
            [[$this->favoriteAttribute], 'default', 'value' => 0],
211 8
            ] : [];
212
    }
213
214
    /**
215
     * Validation rules associated with other guid attribute.
216
     * @return array rules.
217
     */
218 8
    public function getOtherGuidRules()
219
    {
220
        $rules = [
221 8
            [[$this->otherGuidAttribute], 'required'],
222 8
            [[$this->otherGuidAttribute], 'string', 'max' => 36],
223 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...
224 8
        ];
225 8
        return $rules;
226
    }
227
228
    /**
229
     * Attach events associated with user relation.
230
     */
231 8
    public function initUserRelationEvents()
232
    {
233 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...
234 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...
235 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...
236 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...
237 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...
238 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...
239 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...
240 8
    }
241
242
    /**
243
     * Get opposite relation to self.
244
     * @return \vistart\Models\models\BaseUserRelationModel
245
     */
246 7
    public function getOpposite()
247
    {
248 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...
249 1
            return null;
250
        }
251 7
        $createdByAttribute = $this->createdByAttribute;
252 7
        $otherGuidAttribute = $this->otherGuidAttribute;
253 7
        return static::find()->opposite($this->$createdByAttribute, $this->$otherGuidAttribute);
254
    }
255
256
    /**
257
     * Build a suspend mutual relation, not support single relation.
258
     * @param BaseUserModel|string $user Initiator or its GUID.
259
     * @param BaseUserModel|string $other Recipient or its GUID.
260
     * @return \vistart\Models\models\BaseUserRelationModel The relation will be
261
     * given if exists, or return a new relation.
262
     */
263 1
    public static function buildSuspendRelation($user, $other)
264
    {
265 1
        $relation = static::buildRelation($user, $other);
266 1
        $btAttribute = $relation->mutualTypeAttribute;
267 1
        $relation->$btAttribute = static::$mutualTypeSuspend;
268 1
        return $relation;
269
    }
270
271
    /**
272
     * Build a normal relation.
273
     * @param BaseUserModel|string $user Initiator or its GUID.
274
     * @param BaseUserModel|string $other Recipient or its GUID.
275
     * @return \vistart\Models\models\BaseUserRelationModel The relation will be
276
     * given if exists, or return a new relation.
277
     */
278 8
    public static function buildNormalRelation($user, $other)
279
    {
280 8
        $relation = static::buildRelation($user, $other);
281 8
        if ($relation->relationType == static::$relationMutual) {
282 7
            $btAttribute = $relation->mutualTypeAttribute;
283 7
            $relation->$btAttribute = static::$mutualTypeNormal;
284 7
        }
285 8
        return $relation;
286
    }
287
288
    /**
289
     * Build relation between initiator and recipient.
290
     * @param BaseUserModel|string $user Initiator or its GUID.
291
     * @param BaseUserModel|string $other Recipient or its GUID.
292
     * @return \vistart\Models\models\BaseUserRelationModel The relation will be
293
     * given if exists, or return a new relation. Or return null if not allowed
294
     * to build self relation,
295
     */
296 8
    protected static function buildRelation($user, $other)
297
    {
298 8
        $relationQuery = static::find()->initiators($user)->recipients($other);
299 8
        $noInit = $relationQuery->noInitModel;
300 8
        $relation = $relationQuery->one();
301 8
        if (!$relation) {
302 8
            $createdByAttribute = $noInit->createdByAttribute;
303 8
            $otherGuidAttribute = $noInit->otherGuidAttribute;
304 8
            $userClass = $noInit->userClass;
305 8
            if ($user instanceof BaseUserModel) {
306 8
                $userClass = $userClass ? : $user->className();
307 8
                $user = $user->guid;
308 8
            }
309 8
            if ($other instanceof BaseUserModel) {
310 8
                $other = $other->guid;
311 8
            }
312 8
            if (!$noInit->relationSelf && $user == $other) {
313
                return null;
314
            }
315 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...
316 8
        }
317 8
        return $relation;
318
    }
319
320
    /**
321
     * Build opposite relation throughout the current relation. The opposite
322
     * relation will be given if existed.
323
     * @param \vistart\Models\models\BaseUserRelationModel $relation
324
     * @return \vistart\Models\models\BaseUserRelationModel
325
     */
326 7
    protected static function buildOppositeRelation($relation)
327
    {
328 7
        if (!$relation) {
329
            return null;
330
        }
331 7
        $createdByAttribute = $relation->createdByAttribute;
332 7
        $otherGuidAttribute = $relation->otherGuidAttribute;
333 7
        $opposite = static::buildRelation($relation->$otherGuidAttribute, $relation->$createdByAttribute);
334 7
        if ($relation->relationType == static::$relationSingle) {
335
            $opposite->relationType = static::$relationSingle;
336 7
        } elseif ($relation->relationType == static::$relationMutual) {
337 7
            $mutualTypeAttribute = $relation->mutualTypeAttribute;
338 7
            $opposite->$mutualTypeAttribute = $relation->$mutualTypeAttribute;
339 7
        }
340 7
        return $opposite;
341
    }
342
343
    /**
344
     * Remove myself.
345
     * @return integer|false The number of relations removed, or false if the remove
346
     * is unsuccessful for some reason. Note that it is possible the number of relations
347
     * removed is 0, even though the remove execution is successful.
348
     */
349 2
    public function remove()
350
    {
351 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...
352
    }
353
354
    /**
355
     * Remove first relation between initiator(s) and recipient(s).
356
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
357
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
358
     * @return integer|false The number of relations removed.
359
     */
360 1
    public static function removeOneRelation($user, $other)
361
    {
362 1
        return static::find()->initiators($user)->recipients($other)->one()->delete();
363
    }
364
365
    /**
366
     * Remove all relations between initiator(s) and recipient(s).
367
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
368
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
369
     * @return integer The number of relations removed.
370
     */
371 2
    public static function removeAllRelations($user, $other)
372
    {
373 2
        $rni = static::buildNoInitModel();
374 2
        $createdByAttribute = $rni->createdByAttribute;
375 2
        $otherGuidAttribute = $rni->otherGuidAttribute;
376 2
        return static::deleteAll([$createdByAttribute => $user, $otherGuidAttribute => $other]);
377
    }
378
379
    /**
380
     * Get first relation between initiator(s) and recipient(s).
381
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
382
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
383
     * @return \vistart\Models\models\BaseUserRelationModel
384
     */
385 1
    public static function findOneRelation($user, $other)
386
    {
387 1
        return static::find()->initiators($user)->recipients($other)->one();
388
    }
389
390
    /**
391
     * Get first opposite relation between initiator(s) and recipient(s).
392
     * @param BaseUserModel|string $user Initiator or its guid, or array of them.
393
     * @param BaseUserModel|string $other Recipient or its guid, or array of them.
394
     * @return \vistart\Models\models\BaseUserRelationModel
395
     */
396 7
    public static function findOneOppositeRelation($user, $other)
397
    {
398 7
        return static::find()->initiators($other)->recipients($user)->one();
399
    }
400
401
    /**
402
     * Get user's or users' all relations, or by specified groups.
403
     * @param BaseUserModel|string|array $user Initiator or its GUID, or Initiators or their GUIDs.
404
     * @param BaseUserRelationGroupModel|string|array|null $groups UserRelationGroup
405
     * or its guid, or array of them. If you do not want to delimit the groups, please assign null.
406
     * @return array all eligible relations
407
     */
408
    public static function findOnesAllRelations($user, $groups = null)
409
    {
410
        return static::find()->initiators($user)->groups($groups)->all();
411
    }
412
413
    /**
414
     * Initialize groups attribute.
415
     * @param \yii\base\Event $event
416
     */
417 8
    public function onInitGroups($event)
418
    {
419 8
        $sender = $event->sender;
420 8
        $sender->removeAllGroups();
421 8
    }
422
423
    /**
424
     * Initialize remark attribute.
425
     * @param \yii\base\Event $event
426
     */
427 8
    public function onInitRemark($event)
428
    {
429 8
        $sender = $event->sender;
430 8
        $remarkAttribute = $sender->remarkAttribute;
431 8
        is_string($remarkAttribute) ? $sender->$remarkAttribute = '' : null;
432 8
    }
433
434
    /**
435
     * The event triggered after insert new relation.
436
     * The opposite relation should be inserted without triggering events
437
     * simultaneously after new relation inserted,
438
     * @param \yii\base\Event $event
439
     */
440 8
    public function onInsertRelation($event)
441
    {
442 8
        $sender = $event->sender;
443 8
        if ($sender->relationType == static::$relationMutual) {
444 7
            $opposite = static::buildOppositeRelation($sender);
445 7
            $opposite->off(static::EVENT_AFTER_INSERT, [$opposite, 'onInsertRelation']);
446 7
            if (!$opposite->save()) {
447
                $opposite->recordWarnings();
448
            }
449 7
            $opposite->on(static::EVENT_AFTER_INSERT, [$opposite, 'onInsertRelation']);
450 7
        }
451 8
    }
452
453
    /**
454
     * The event triggered after update relation.
455
     * The opposite relation should be updated without triggering events
456
     * simultaneously after existed relation removed.
457
     * @param \yii\base\Event $event
458
     */
459 3
    public function onUpdateRelation($event)
460
    {
461 3
        $sender = $event->sender;
462 3
        if ($sender->relationType == static::$relationMutual) {
463 3
            $opposite = static::buildOppositeRelation($sender);
464 3
            $opposite->off(static::EVENT_AFTER_UPDATE, [$opposite, 'onUpdateRelation']);
465 3
            if (!$opposite->save()) {
466
                $opposite->recordWarnings();
467
            }
468 3
            $opposite->on(static::EVENT_AFTER_UPDATE, [$opposite, 'onUpdateRelation']);
469 3
        }
470 3
    }
471
472
    /**
473
     * The event triggered after delete relation.
474
     * The opposite relation should be deleted without triggering events
475
     * simultaneously after existed relation removed.
476
     * @param \yii\base\Event $event
477
     */
478 2
    public function onDeleteRelation($event)
479
    {
480 2
        $sender = $event->sender;
481 2
        if ($sender->relationType == static::$relationMutual) {
482 2
            $createdByAttribute = $sender->createdByAttribute;
483 2
            $otherGuidAttribute = $sender->otherGuidAttribute;
484 2
            $sender->off(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
485 2
            static::removeAllRelations($sender->$otherGuidAttribute, $sender->$createdByAttribute);
486 2
            $sender->on(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
487 2
        }
488 2
    }
489
}
490