Completed
Push — master ( 31342d...eef2a4 )
by vistart
05:36
created

UserRelationTrait::getOpposite()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 8
Bugs 0 Features 0
Metric Value
c 8
b 0
f 0
dl 0
loc 9
ccs 6
cts 6
cp 1
rs 9.6666
cc 2
eloc 6
nc 2
nop 0
crap 2
1
<?php
2
3
/**
4
 *  _   __ __ _____ _____ ___  ____  _____
5
 * | | / // // ___//_  _//   ||  __||_   _|
6
 * | |/ // /(__  )  / / / /| || |     | |
7
 * |___//_//____/  /_/ /_/ |_||_|     |_|
8
 * @link http://vistart.name/
9
 * @copyright Copyright (c) 2016 vistart
10
 * @license http://vistart.name/license/
11
 */
12
13
namespace vistart\Models\traits;
14
15
use vistart\Models\models\BaseUserModel;
16
use vistart\Models\traits\MultipleBlameableTrait as mb;
17
18
/**
19
 * Relation features.
20
 * Note: Several methods associated with "inserting", "updating" and "removing" may
21
 * involve more DB operations, I strongly recommend those methods to be placed in
22
 * transaction execution, in order to ensure data consistency.
23
 * If you want to use group feature, the class used [[UserRelationGroupTrait]]
24
 * must be used coordinately.
25
 * @property array $groupGuids the guid array of all groups which owned by current relation.
26
 * @property-read array $allGroups
27
 * @property-read array $nonGroupMembers
28
 * @property-read integer $groupsCount
29
 * @property-read array $groupsRules
30
 * @property boolean $isFavorite
31
 * @property-read \vistart\Models\models\BaseUserRelationModel $opposite
32
 * @version 2.0
33
 * @author vistart <[email protected]>
34
 */
35
trait UserRelationTrait
36
{
37
    use mb {
38
        mb::addBlame as addGroup;
39
        mb::createBlame as createGroup;
40
        mb::addOrCreateBlame as addOrCreateGroup;
41
        mb::removeBlame as removeGroup;
42
        mb::removeAllBlames as removeAllGroups;
43
        mb::getBlame as getGroup;
44
        mb::getOrCreateBlame as getOrCreateGroup;
45
        mb::getBlameds as getGroupMembers;
46
        mb::getBlameGuids as getGroupGuids;
47
        mb::setBlameGuids as setGroupGuids;
48
        mb::getAllBlames as getAllGroups;
49
        mb::getNonBlameds as getNonGroupMembers;
50
        mb::getBlamesCount as getGroupsCount;
51
        mb::getMultipleBlameableAttributeRules as getGroupsRules;
52
        mb::getEmptyBlamesJson as getEmptyGroupJson;
53
    }
54
55
    /**
56
     * @var string the another party of the relation.
57
     */
58
    public $otherGuidAttribute = 'other_guid';
59
60
    /**
61
     * @var string
62
     */
63
    public $remarkAttribute = 'remark';
64
    public static $relationSingle = 0;
65
    public static $relationMutual = 1;
66
    public $relationType = 1;
67
    public $relationTypes = [
68
        0 => 'Single',
69
        1 => 'Mutual',
70
    ];
71
72
    /**
73
     * @var string the attribute name of which determines the relation type.
74
     */
75
    public $mutualTypeAttribute = 'type';
76
    public static $mutualTypeNormal = 0x00;
77
    public static $mutualTypeSuspend = 0x01;
78
79
    /**
80
     * @var array Mutual types.
81
     */
82
    public static $mutualTypes = [
83
        0x00 => 'Normal',
84
        0x01 => 'Suspend',
85
    ];
86
87
    /**
88
     * @var string the attribute name of which determines the `favorite` field.
89
     */
90
    public $favoriteAttribute = 'favorite';
91
92
    /**
93
     * Get whether this relation is favorite or not.
94
     * @return boolean
95
     */
96 1
    public function getIsFavorite()
97
    {
98 1
        $favoriteAttribute = $this->favoriteAttribute;
99 1
        return is_string($favoriteAttribute) ? (int) $this->$favoriteAttribute > 0 : null;
100
    }
101
102
    /**
103
     * Set favorite.
104
     * @param boolean $fav
105
     */
106 1
    public function setIsFavorite($fav)
107
    {
108 1
        $favoriteAttribute = $this->favoriteAttribute;
109 1
        return is_string($favoriteAttribute) ? $this->$favoriteAttribute = ($fav ? 1 : 0) : null;
110
    }
111
112
    /**
113
     * @inheritdoc
114
     */
115 8
    public function rules()
116
    {
117 8
        return array_merge(parent::rules(), $this->getUserRelationRules());
118
    }
119
120
    /**
121
     * Validation rules associated with user relation.
122
     * @return array rules.
123
     */
124 8
    public function getUserRelationRules()
125
    {
126 8
        $rules = [];
127 8
        if ($this->relationType == static::$relationMutual) {
128
            $rules = [
129 7
                [[$this->mutualTypeAttribute], 'in', 'range' => array_keys(static::$mutualTypes)],
130 7
                [[$this->mutualTypeAttribute], 'default', 'value' => static::$mutualTypeNormal],
131 7
            ];
132 7
        }
133 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...
134
    }
135
136
    /**
137
     * Get remark.
138
     * @return string remark.
139
     */
140
    public function getRemark()
141
    {
142
        $remarkAttribute = $this->remarkAttribute;
143
        return is_string($remarkAttribute) ? $this->$remarkAttribute : null;
144
    }
145
146
    /**
147
     * Set remark.
148
     * @param string $remark
149
     * @return string remark.
150
     */
151
    public function setRemark($remark)
152
    {
153
        $remarkAttribute = $this->remarkAttribute;
154
        return is_string($remarkAttribute) ? $this->$remarkAttribute = $remark : null;
155
    }
156
157
    /**
158
     * Validation rules associated with remark attribute.
159
     * @return array rules.
160
     */
161 8
    public function getRemarkRules()
162
    {
163 8
        return is_string($this->remarkAttribute) ? [
164 8
            [[$this->remarkAttribute], 'string'],
165 8
            [[$this->remarkAttribute], 'default', 'value' => ''],
166 8
            ] : [];
167
    }
168
169
    /**
170
     * Validation rules associated with favorites attribute.
171
     * @return array rules.
172
     */
173 8
    public function getFavoriteRules()
174
    {
175 8
        return is_string($this->favoriteAttribute) ? [
176 8
            [[$this->favoriteAttribute], 'boolean'],
177 8
            [[$this->favoriteAttribute], 'default', 'value' => 0],
178 8
            ] : [];
179
    }
180
181
    /**
182
     * Validation rules associated with other guid attribute.
183
     * @return array rules.
184
     */
185 8
    public function getOtherGuidRules()
186
    {
187
        $rules = [
188 8
            [[$this->otherGuidAttribute], 'required'],
189 8
            [[$this->otherGuidAttribute], 'string', 'max' => 36],
190 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...
191 8
        ];
192 8
        return $rules;
193
    }
194
195
    /**
196
     * Attach events associated with user relation.
197
     */
198 8
    public function initUserRelationEvents()
199
    {
200 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...
201 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...
202 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...
203 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...
204 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...
205 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...
206 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...
207 8
    }
208
209
    /**
210
     * Get opposite relation to self.
211
     * @return \vistart\Models\models\BaseUserRelationModel
212
     */
213 7
    public function getOpposite()
214
    {
215 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...
216 1
            return null;
217
        }
218 7
        $createdByAttribute = $this->createdByAttribute;
219 7
        $otherGuidAttribute = $this->otherGuidAttribute;
220 7
        return static::find()->opposite($this->$createdByAttribute, $this->$otherGuidAttribute);
221
    }
222
223
    /**
224
     * Build a suspend mutual relation, not support single relation.
225
     * @param BaseUserModel|string $user Initiator or its GUID.
226
     * @param BaseUserModel|string $other Recipient or its GUID.
227
     * @return \vistart\Models\models\BaseUserRelationModel The relation will be
228
     * given if exists, or return a new relation.
229
     */
230 1
    public static function buildSuspendRelation($user, $other)
231
    {
232 1
        $relation = static::buildRelation($user, $other);
233 1
        $btAttribute = $relation->mutualTypeAttribute;
234 1
        $relation->$btAttribute = static::$mutualTypeSuspend;
235 1
        return $relation;
236
    }
237
238
    /**
239
     * Build a normal relation.
240
     * @param BaseUserModel|string $user Initiator or its GUID.
241
     * @param BaseUserModel|string $other Recipient or its GUID.
242
     * @return \vistart\Models\models\BaseUserRelationModel The relation will be
243
     * given if exists, or return a new relation.
244
     */
245 8
    public static function buildNormalRelation($user, $other)
246
    {
247 8
        $relation = static::buildRelation($user, $other);
248 8
        if ($relation->relationType == static::$relationMutual) {
249 7
            $btAttribute = $relation->mutualTypeAttribute;
250 7
            $relation->$btAttribute = static::$mutualTypeNormal;
251 7
        }
252 8
        return $relation;
253
    }
254
255
    /**
256
     * Build relation between initiator and recipient.
257
     * @param BaseUserModel|string $user Initiator or its GUID.
258
     * @param BaseUserModel|string $other Recipient or its GUID.
259
     * @return \vistart\Models\models\BaseUserRelationModel The relation will be
260
     * given if exists, or return a new relation.
261
     */
262 8
    protected static function buildRelation($user, $other)
263
    {
264 8
        $relationQuery = static::find()->initiators($user)->recipients($other);
265 8
        $noInit = $relationQuery->noInitModel;
266 8
        $relation = $relationQuery->one();
267 8
        if (!$relation) {
268 8
            $createdByAttribute = $noInit->createdByAttribute;
269 8
            $otherGuidAttribute = $noInit->otherGuidAttribute;
270 8
            $userClass = $noInit->userClass;
271 8
            if ($user instanceof BaseUserModel) {
272 8
                $userClass = $userClass ? : $user->className();
273 8
                $user = $user->guid;
274 8
            }
275 8
            if ($other instanceof BaseUserModel) {
276 8
                $other = $other->guid;
277 8
            }
278 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...
279 8
        }
280 8
        return $relation;
281
    }
282
283
    /**
284
     * Build opposite relation throughout the current relation. The opposite
285
     * relation will be given if existed.
286
     * @param \vistart\Models\models\BaseUserRelationModel $relation
287
     * @return \vistart\Models\models\BaseUserRelationModel
288
     */
289 7
    protected static function buildOppositeRelation($relation)
290
    {
291 7
        if (!$relation) {
292
            return null;
293
        }
294 7
        $createdByAttribute = $relation->createdByAttribute;
295 7
        $otherGuidAttribute = $relation->otherGuidAttribute;
296 7
        $opposite = static::buildRelation($relation->$otherGuidAttribute, $relation->$createdByAttribute);
297 7
        if ($relation->relationType == static::$relationSingle) {
298
            $opposite->relationType = static::$relationSingle;
299 7
        } elseif ($relation->relationType == static::$relationMutual) {
300 7
            $mutualTypeAttribute = $relation->mutualTypeAttribute;
301 7
            $opposite->$mutualTypeAttribute = $relation->$mutualTypeAttribute;
302 7
        }
303 7
        return $opposite;
304
    }
305
306
    /**
307
     * Remove myself.
308
     * @return integer|false The number of relations removed, or false if the remove
309
     * is unsuccessful for some reason. Note that it is possible the number of relations
310
     * removed is 0, even though the remove execution is successful.
311
     */
312 2
    public function remove()
313
    {
314 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...
315
    }
316
317
    /**
318
     * Remove first relation between initiator(s) and recipient(s).
319
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
320
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
321
     * @return integer|false The number of relations removed.
322
     */
323 1
    public static function removeOneRelation($user, $other)
324
    {
325 1
        return static::find()->initiators($user)->recipients($other)->one()->delete();
326
    }
327
328
    /**
329
     * Remove all relations between initiator(s) and recipient(s).
330
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
331
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
332
     * @return integer The number of relations removed.
333
     */
334 2
    public static function removeAllRelations($user, $other)
335
    {
336 2
        $rni = static::buildNoInitModel();
337 2
        $createdByAttribute = $rni->createdByAttribute;
338 2
        $otherGuidAttribute = $rni->otherGuidAttribute;
339 2
        return static::deleteAll([$createdByAttribute => $user, $otherGuidAttribute => $other]);
340
    }
341
342
    /**
343
     * Get first relation between initiator(s) and recipient(s).
344
     * @param BaseUserModel|string|array $user Initiator or its guid, or array of them.
345
     * @param BaseUserModel|string|array $other Recipient or its guid, or array of them.
346
     * @return \vistart\Models\models\BaseUserRelationModel
347
     */
348 1
    public static function findOneRelation($user, $other)
349
    {
350 1
        return static::find()->initiators($user)->recipients($other)->one();
351
    }
352
353
    /**
354
     * Get first opposite relation between initiator(s) and recipient(s).
355
     * @param BaseUserModel|string $user Initiator or its guid, or array of them.
356
     * @param BaseUserModel|string $other Recipient or its guid, or array of them.
357
     * @return \vistart\Models\models\BaseUserRelationModel
358
     */
359 7
    public static function findOneOppositeRelation($user, $other)
360
    {
361 7
        return static::find()->initiators($other)->recipients($user)->one();
362
    }
363
364
    /**
365
     * Get user's or users' all relations, or by specified groups.
366
     * @param BaseUserModel|string|array $user Initiator or its GUID, or Initiators or their GUIDs.
367
     * @param BaseUserRelationGroupModel|string|array|null $groups UserRelationGroup or its guid, or array of them. If you do not want to delimit the groups, please assign null.
368
     * @return array all eligible relations
369
     */
370
    public static function findOnesAllRelations($user, $groups = null)
371
    {
372
        return static::find()->initiators($user)->groups($groups)->all();
373
    }
374
375
    /**
376
     * Initialize groups attribute.
377
     * @param \yii\base\Event $event
378
     */
379 8
    public function onInitGroups($event)
380
    {
381 8
        $sender = $event->sender;
382 8
        $sender->removeAllGroups();
383 8
    }
384
385
    /**
386
     * Initialize remark attribute.
387
     * @param \yii\base\Event $event
388
     */
389 8
    public function onInitRemark($event)
390
    {
391 8
        $sender = $event->sender;
392 8
        $remarkAttribute = $sender->remarkAttribute;
393 8
        is_string($remarkAttribute) ? $sender->$remarkAttribute = '' : null;
394 8
    }
395
396
    /**
397
     * The event triggered after insert new relation.
398
     * The opposite relation should be inserted without triggering events
399
     * simultaneously after new relation inserted,
400
     * @param \yii\base\Event $event
401
     */
402 8
    public function onInsertRelation($event)
403
    {
404 8
        $sender = $event->sender;
405 8
        if ($sender->relationType == static::$relationMutual) {
406 7
            $opposite = static::buildOppositeRelation($sender);
407 7
            $opposite->off(static::EVENT_AFTER_INSERT, [$opposite, 'onInsertRelation']);
408 7
            if (!$opposite->save()) {
409
                $opposite->recordWarnings();
410
            }
411 7
            $opposite->on(static::EVENT_AFTER_INSERT, [$opposite, 'onInsertRelation']);
412 7
        }
413 8
    }
414
415
    /**
416
     * The event triggered after update relation.
417
     * The opposite relation should be updated without triggering events
418
     * simultaneously after existed relation removed.
419
     * @param \yii\base\Event $event
420
     */
421 3
    public function onUpdateRelation($event)
422
    {
423 3
        $sender = $event->sender;
424 3
        if ($sender->relationType == static::$relationMutual) {
425 3
            $opposite = static::buildOppositeRelation($sender);
426 3
            $opposite->off(static::EVENT_AFTER_UPDATE, [$opposite, 'onUpdateRelation']);
427 3
            if (!$opposite->save()) {
428
                $opposite->recordWarnings();
429
            }
430 3
            $opposite->on(static::EVENT_AFTER_UPDATE, [$opposite, 'onUpdateRelation']);
431 3
        }
432 3
    }
433
434
    /**
435
     * The event triggered after delete relation.
436
     * The opposite relation should be deleted without triggering events
437
     * simultaneously after existed relation removed.
438
     * @param \yii\base\Event $event
439
     */
440 2
    public function onDeleteRelation($event)
441
    {
442 2
        $sender = $event->sender;
443 2
        if ($sender->relationType == static::$relationMutual) {
444 2
            $createdByAttribute = $sender->createdByAttribute;
445 2
            $otherGuidAttribute = $sender->otherGuidAttribute;
446 2
            $sender->off(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
447 2
            static::removeAllRelations($sender->$otherGuidAttribute, $sender->$createdByAttribute);
448 2
            $sender->on(static::EVENT_AFTER_DELETE, [$sender, 'onDeleteRelation']);
449 2
        }
450 2
    }
451
}
452