Completed
Push — master ( 94bfdc...ad0b21 )
by vistart
06:15
created

SelfBlameableTrait::setRefId()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
ccs 0
cts 6
cp 0
rs 9.4285
cc 3
eloc 6
nc 3
nop 1
crap 12
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 yii\base\ModelEvent;
16
use yii\base\InvalidConfigException;
17
use yii\base\InvalidParamException;
18
use yii\db\ActiveQuery;
19
use yii\db\IntegrityException;
20
21
/**
22
 * This trait is designed for the model who contains parent.
23
 * The BlameableTrait use this trait by default. If you want to use this trait
24
 * into seperate model, please call the `initSelfBlameableEvents()` method in
25
 * `init()` method, like following:
26
 * ```php
27
 * public function init()
28
 * {
29
 *     $this->initSelfBlameableEvents();  // put it before parent call.
30
 *     parent::init();
31
 * }
32
 * ```
33
 *
34
 * @property static $parent
35
 * @property-read static[] $ancestors
36
 * @property-read string[] $ancestorChain
37
 * @property-read array $ancestorModels
38
 * @property-read static $commonAncestor
39
 * @property-read static[] $children
40
 * @property-read static[] $oldChildren
41
 * @property array $selfBlameableRules
42
 * @version 1.0
43
 * @author vistart <[email protected]>
44
 */
45
trait SelfBlameableTrait
46
{
47
48
    /**
49
     * @var false|string attribute name of which store the parent's guid.
50
     * If you do not want to use self-blameable features, please set it false.
51
     * Or if you access any features of this trait when this parameter is false,
52
     * exception may be thrown.
53
     */
54
    public $parentAttribute = false;
55
56
    /**
57
     * @var string|array rule name and parameters of parent attribute, as well
58
     * as self referenced ID attribute.
59
     */
60
    public $parentAttributeRule = ['string', 'max' => 16];
61
62
    /**
63
     * @var string self referenced ID attribute.
64
     * If you enable self-blameable features, this parameter should be specified,
65
     * otherwise, exception will be thrown.
66
     */
67
    public $refIdAttribute = 'guid';
68
    public static $parentNone = 0;
69
    public static $parentParent = 1;
70
    public static $parentTypes = [
71
        0 => 'none',
72
        1 => 'parent',
73
    ];
74
    public static $nullParent = '';
75
    public static $onNoAction = 0;
76
    public static $onRestrict = 1;
77
    public static $onCascade = 2;
78
    public static $onSetNull = 3;
79
    public static $onUpdateTypes = [
80
        0 => 'on action',
81
        1 => 'restrict',
82
        2 => 'cascade',
83
        3 => 'set null',
84
    ];
85
86
    /**
87
     * @var integer indicates the on delete type. default to cascade.
88
     */
89
    public $onDeleteType = 2;
90
91
    /**
92
     * @var integer indicates the on update type. default to cascade.
93
     */
94
    public $onUpdateType = 2;
95
96
    /**
97
     * @var boolean indicates whether throw exception or not when restriction occured on updating or deleting operation.
98
     */
99
    public $throwRestrictException = false;
100
    
101
    /**
102
     * @var array store the attribute validation rules.
103
     * If this field is a non-empty array, then it will be given.
104
     */
105
    private $localSelfBlameableRules = [];
106
    public static $eventParentChanged = 'parentChanged';
107
    public static $eventChildAdded = 'childAdded';
108
109
    /**
110
     * @var false|integer Set the limit of ancestor level. False is no limit.
111
     * We strongly recommend you set an unsigned integer which is less than 256.
112
     */
113
    public $ancestorLimit = false;
114
115
    /**
116
     * @var false|integer Set the limit of children (not descendants). False is no limit.
117
     * We strongly recommend you set an unsigned integer which is less than 1024.
118
     */
119
    public $childrenLimit = false;
120
121
    /**
122
     * Get rules associated with self blameable attribute.
123
     * If self-blameable rules has been stored locally, then it will be given,
124
     * or return the parent attribute rule.
125
     * @return array rules.
126
     */
127 117
    public function getSelfBlameableRules()
128
    {
129 117
        if (!is_string($this->parentAttribute)) {
130 117
            return [];
131
        }
132 36
        if (!empty($this->localSelfBlameableRules) && is_array($this->localSelfBlameableRules)) {
133 2
            return $this->localSelfBlameableRules;
134
        }
135 36
        if (is_string($this->parentAttributeRule)) {
136
            $this->parentAttributeRule = [$this->parentAttributeRule];
137
        }
138 36
        $this->localSelfBlameableRules = [
139 36
            array_merge([$this->parentAttribute], $this->parentAttributeRule),
140
        ];
141 36
        return $this->localSelfBlameableRules;
142
    }
143
144
    /**
145
     * Set rules associated with self blameable attribute.
146
     * @param array $rules rules.
147
     */
148 1
    public function setSelfBlameableRules($rules = [])
149
    {
150 1
        $this->localSelfBlameableRules = $rules;
151 1
    }
152
153
    /**
154
     * Check whether this model has reached the ancestor limit.
155
     * If $ancestorLimit is false, it will be regared as no limit(return false).
156
     * If $ancestorLimit is not false and not an unsigned integer, 256 will be taken.
157
     * @return boolean
158
     */
159 46
    public function hasReachedAncestorLimit()
160
    {
161 46
        if ($this->ancestorLimit === false) {
162 46
            return false;
163
        }
164 3
        if (!is_numeric($this->ancestorLimit) || $this->ancestorLimit < 0) {
165 1
            $this->ancestorLimit = 256;
166
        }
167 3
        return count($this->getAncestorChain()) >= $this->ancestorLimit;
168
    }
169
170
    /**
171
     * Check whether this model has reached the children limit.
172
     * If $childrenLimit is false, it will be regarded as no limit(return false).
173
     * If $childrenLimit is not false and not an unsigned integer, 1024 will be taken.
174
     * @return boolean
175
     */
176 4
    public function hasReachedChildrenLimit()
177
    {
178 4
        if ($this->childrenLimit === false) {
179 4
            return false;
180
        }
181 1
        if (!is_numeric($this->childrenLimit) || $this->childrenLimit < 0) {
182 1
            $this->childrenLimit = 1024;
183
        }
184 1
        return ((int) $this->getChildren()->count()) >= $this->childrenLimit;
185
    }
186
187
    /**
188
     * Bear a child.
189
     * The creator of this child is not necessarily the creator of current one.
190
     * For example: Someone commit a comment on another user's comment, these
191
     * two comments are father and son, but do not belong to the same owner.
192
     * Therefore, you need to specify the creator of current model.
193
     * @param array $config
194
     * @return static|null Null if reached the ancestor limit or children limit.
195
     * @throws InvalidConfigException Self reference ID attribute or
196
     * parent attribute not determined.
197
     * @throws InvalidParamException ancestor or children limit reached.
198
     */
199 4
    public function bear($config = [])
200
    {
201 4
        if (!$this->parentAttribute) {
202 1
            throw new InvalidConfigException("Parent Attribute Not Determined.");
203
        }
204 3
        if (!$this->refIdAttribute) {
205
            throw new InvalidConfigException("Self Reference ID Attribute Not Determined.");
206
        }
207 3
        if ($this->hasReachedAncestorLimit()) {
208
            throw new InvalidParamException("Reached Ancestor Limit: " . $this->ancestorLimit);
209
        }
210 3
        if ($this->hasReachedChildrenLimit()) {
211
            throw new InvalidParamException("Reached Children Limit: ". $this->childrenLimit);
212
        }
213 3
        if (isset($config['class'])) {
214
            unset($config['class']);
215
        }
216 3
        $model = new static($config);
0 ignored issues
show
Unused Code introduced by
The call to SelfBlameableTrait::__construct() has too many arguments starting with $config.

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...
217 3
        if ($this->addChild($model) === false) {
218
            return false;
219
        }
220 3
        return $model;
221
    }
222
223
    /**
224
     * Add a child.
225
     * @param static $child
0 ignored issues
show
introduced by
The type SelfBlameableTrait for parameter $child 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...
226
     * @return boolean
227
     */
228 3
    public function addChild($child)
229
    {
230 3
        return $this->hasReachedChildrenLimit() ? false : $child->setParent($this);
231
    }
232
233
    /**
234
     * Event triggered before deleting itself.
235
     * @param ModelEvent $event
236
     * @return boolean true if parentAttribute not specified.
237
     * @throws IntegrityException throw if $throwRestrictException is true when $onDeleteType is on restrict.
238
     */
239 55
    public function onDeleteChildren($event)
240
    {
241 55
        $sender = $event->sender;
242
        /* @var $sender static */
243 55
        if (empty($sender->parentAttribute) || !is_string($sender->parentAttribute)) {
244 49
            return true;
245
        }
246 6
        switch ($sender->onDeleteType) {
247 6
            case static::$onRestrict:
248 1
                $event->isValid = $sender->children === null;
249 1
                if ($this->throwRestrictException) {
250 1
                    throw new IntegrityException('Delete restricted.');
251
                }
252 1
                break;
253 5
            case static::$onCascade:
254 3
                $event->isValid = $sender->deleteChildren();
0 ignored issues
show
Documentation Bug introduced by
It seems like $sender->deleteChildren() can also be of type object<yii\db\IntegrityException>. However, the property $isValid is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
255 3
                break;
256 2
            case static::$onSetNull:
257 1
                $event->isValid = $sender->updateChildren(null);
0 ignored issues
show
Documentation Bug introduced by
It seems like $sender->updateChildren(null) can also be of type object<yii\db\IntegrityException>. However, the property $isValid is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
258 1
                break;
259 1
            case static::$onNoAction:
260
            default:
261 1
                $event->isValid = true;
262 1
                break;
263
        }
264 6
    }
265
266
    /**
267
     * Event triggered before updating itself.
268
     * @param ModelEvent $event
269
     * @return boolean true if parentAttribute not specified.
270
     * @throws IntegrityException throw if $throwRestrictException is true when $onUpdateType is on restrict.
271
     */
272 4
    public function onUpdateChildren($event)
273
    {
274 4
        $sender = $event->sender;
275
        /* @var $sender static */
276 4
        if (empty($sender->parentAttribute) || !is_string($sender->parentAttribute)) {
277
            return true;
278
        }
279 4
        switch ($sender->onUpdateType) {
280 4
            case static::$onRestrict:
281 1
                $event->isValid = $sender->getOldChildren() === null;
282 1
                if ($this->throwRestrictException) {
283 1
                    throw new IntegrityException('Update restricted.');
284
                }
285 1
                break;
286 3
            case static::$onCascade:
287 1
                $event->isValid = $sender->updateChildren();
0 ignored issues
show
Documentation Bug introduced by
It seems like $sender->updateChildren() can also be of type object<yii\db\IntegrityException>. However, the property $isValid is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
288 1
                break;
289 2
            case static::$onSetNull:
290 1
                $event->isValid = $sender->updateChildren(null);
0 ignored issues
show
Documentation Bug introduced by
It seems like $sender->updateChildren(null) can also be of type object<yii\db\IntegrityException>. However, the property $isValid is declared as type boolean. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
291 1
                break;
292 1
            case static::$onNoAction:
293
            default:
294 1
                $event->isValid = true;
295 1
                break;
296
        }
297 4
    }
298
299
    /**
300
     * Get parent query.
301
     * Or get parent instance if access by magic property.
302
     * @return ActiveQuery
303
     */
304 46
    public function getParent()
305
    {
306 46
        return $this->hasOne(static::class, [$this->refIdAttribute => $this->parentAttribute]);
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...
307
    }
308
    
309 4
    public function getParentId()
310
    {
311 4
        return (is_string($this->parentAttribute) && !empty($this->parentAttribute)) ? $this->{$this->parentAttribute} : null;
312
    }
313
    
314 4
    public function setParentId($id)
315
    {
316 4
        return (is_string($this->parentAttribute) && !empty($this->parentAttribute)) ? $this->{$this->parentAttribute} = $id : null;
317
    }
318
    
319 46
    public function getRefId()
320
    {
321 46
        if ($this->refIdAttribute == $this->guidAttribute) {
0 ignored issues
show
Bug introduced by
The property guidAttribute 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...
322 46
            return $this->getGUID();
0 ignored issues
show
Bug introduced by
It seems like getGUID() 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...
323
        }
324
        if ($this->refIdAttribute == $this->idAttribute) {
0 ignored issues
show
Bug introduced by
The property idAttribute does not seem to exist. Did you mean refIdAttribute?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
325
            return $this->getID();
0 ignored issues
show
Bug introduced by
It seems like getID() 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...
326
        }
327
        return $this->{$this->refIdAttribute};
328
    }
329
    
330
    public function setRefId($id)
331
    {
332
        if ($this->refIdAttribute == $this->guidAttribute) {
333
            return $this->setGUID($id);
0 ignored issues
show
Bug introduced by
It seems like setGUID() 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...
334
        }
335
        if ($this->refIdAttribute == $this->idAttribute) {
0 ignored issues
show
Bug introduced by
The property idAttribute does not seem to exist. Did you mean refIdAttribute?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
336
            return $this->setID($id);
0 ignored issues
show
Bug introduced by
It seems like setID() 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...
337
        }
338
        return $this->{$this->refIdAttribute} = $id;
339
    }
340
341
    /**
342
     * Set parent.
343
     * Don't forget save model after setting it.
344
     * @param static $parent
0 ignored issues
show
introduced by
The type SelfBlameableTrait for parameter $parent 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...
345
     * @return false|string False if restriction reached. Otherwise parent's GUID given.
346
     */
347 46
    public function setParent($parent)
348
    {
349 46
        if (empty($parent) || $this->getRefId() == $parent->getRefId() || $parent->hasAncestor($this) || $this->hasReachedAncestorLimit()) {
350 1
            return false;
351
        }
352 46
        unset($this->parent);
353 46
        unset($parent->children);
354 46
        $this->trigger(static::$eventParentChanged);
0 ignored issues
show
Bug introduced by
It seems like trigger() 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...
355 46
        $parent->trigger(static::$eventChildAdded);
0 ignored issues
show
Bug introduced by
It seems like trigger() 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...
356 46
        return $this->{$this->parentAttribute} = $parent->getRefId();
357
    }
358
    
359
    /**
360
     * Set null parent.
361
     */
362 4
    public function setNullParent()
363
    {
364 4
        if ($this->hasParent()) {
365 2
            unset($this->parent->children);
366
        }
367 4
        unset($this->parent);
368 4
        $this->setParentId(static::$nullParent);
369 4
    }
370
371
    /**
372
     * Check whether this model has parent.
373
     * @return boolean
374
     */
375 46
    public function hasParent()
376
    {
377 46
        return $this->parent !== null;
378
    }
379
380
    /**
381
     * Check whether if $ancestor is the ancestor of myself.
382
     * Note, Itself will not be regarded as the its ancestor.
383
     * @param static $ancestor
0 ignored issues
show
introduced by
The type SelfBlameableTrait for parameter $ancestor 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...
384
     * @return boolean
385
     */
386 46
    public function hasAncestor($ancestor)
387
    {
388 46
        if (!$this->hasParent()) {
389 46
            return false;
390
        }
391 6
        if ($this->parent->getRefId() == $ancestor->getRefId()) {
392 2
            return true;
393
        }
394 6
        return $this->parent->hasAncestor($ancestor);
395
    }
396
397
    /**
398
     * Get ancestor chain. (Ancestors' GUID Only!)
399
     * If this model has ancestor, the return array consists all the ancestor in order.
400
     * The first element is parent, and the last element is root, otherwise return empty array.
401
     * If you want to get ancestor model, you can simplify instance a query and specify the
402
     * condition with the return value. But it will not return models under the order of ancestor chain.
403
     * @param string[] $ancestor
404
     * @return string[]
405
     */
406 8
    public function getAncestorChain($ancestor = [])
407
    {
408 8
        if (!is_string($this->parentAttribute) || empty($this->parentAttribute)) {
409 1
            return [];
410
        }
411 7
        if (!$this->hasParent()) {
412 7
            return $ancestor;
413
        }
414 7
        $ancestor[] = $this->parent->getRefId();
415 7
        return $this->parent->getAncestorChain($ancestor);
416
    }
417
418
    /**
419
     * Get ancestors with specified ancestor chain.
420
     * @param string[] $ancestor Ancestor chain.
421
     * @return static[]|null
422
     */
423 2
    public static function getAncestorModels($ancestor)
424
    {
425 2
        if (empty($ancestor) || !is_array($ancestor)) {
426 1
            return [];
427
        }
428 2
        $models = [];
429 2
        foreach ($ancestor as $self) {
430 2
            $models[] = static::findOne($self);
431
        }
432 2
        return $models;
433
    }
434
435
    /**
436
     * Get ancestors.
437
     * @return static[]
438
     */
439 1
    public function getAncestors()
440
    {
441 1
        return static::getAncestorModels($this->getAncestorChain());
442
    }
443
444
    /**
445
     * Check whether if this model has common ancestor with $model.
446
     * @param static $model
0 ignored issues
show
introduced by
The type SelfBlameableTrait for parameter $model 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...
447
     * @return boolean
448
     */
449 2
    public function hasCommonAncestor($model)
450
    {
451 2
        return $this->getCommonAncestor($model) !== null;
452
    }
453
454
    /**
455
     * Get common ancestor. If there isn't common ancestor, null will be given.
456
     * @param static $model
0 ignored issues
show
introduced by
The type SelfBlameableTrait for parameter $model 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...
457
     * @return static
458
     */
459 3
    public function getCommonAncestor($model)
460
    {
461 3
        if (empty($this->parentAttribute) || !is_string($this->parentAttribute) || empty($model) || !$model->hasParent()) {
462 1
            return null;
463
        }
464 2
        $ancestor = $this->getAncestorChain();
465 2
        if (in_array($model->parent->getRefId(), $ancestor)) {
466 2
            return $model->parent;
467
        }
468 1
        return $this->getCommonAncestor($model->parent);
469
    }
470
471
    /**
472
     * Get children query.
473
     * Or get children instances if access magic property.
474
     * @return ActiveQuery
475
     */
476 46
    public function getChildren()
477
    {
478 46
        return $this->hasMany(static::class, [$this->parentAttribute => $this->refIdAttribute])->inverseOf('parent');
0 ignored issues
show
Bug introduced by
It seems like hasMany() 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...
479
    }
480
481
    /**
482
     * Get children which parent attribute point to old guid.
483
     * @return static[]
484
     */
485 4
    public function getOldChildren()
486
    {
487 4
        return static::find()->where([$this->parentAttribute => $this->getOldAttribute($this->refIdAttribute)])->all();
0 ignored issues
show
Bug introduced by
It seems like getOldAttribute() 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...
488
    }
489
490
    /**
491
     * Update all children, not grandchildren (descendants).
492
     * If onUpdateType is on cascade, the children will be updated automatically.
493
     * @param mixed $value set guid if false, set empty string if empty() return
494
     * true, otherwise set it to $parentAttribute.
495
     * @return IntegrityException|boolean true if all update operations
496
     * succeeded to execute, or false if anyone of them failed. If not production
497
     * environment or enable debug mode, it will return exception.
498
     * @throws IntegrityException throw if anyone update failed.
499
     * The exception message only contains the first error.
500
     */
501 3
    public function updateChildren($value = false)
502
    {
503 3
        $children = $this->getOldChildren();
504 3
        if (empty($children)) {
505
            return true;
506
        }
507 3
        $transaction = $this->getDb()->beginTransaction();
0 ignored issues
show
Bug introduced by
It seems like getDb() 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...
508
        try {
509 3
            foreach ($children as $child) {
510
                /* @var $child static */
511 3
                if ($value === false) {
512 1
                    $child->setParent($this);
513
                } elseif (empty($value)) {
514 2
                    $child->setNullParent();
515
                } else {
516
                    $child->setParentId($value);
517
                }
518 3
                if (!$child->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...
519 3
                    throw new IntegrityException('Update failed:', $child->getErrors());
0 ignored issues
show
Bug introduced by
It seems like getErrors() 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...
520
                }
521
            }
522 3
            $transaction->commit();
523
        } catch (IntegrityException $ex) {
524
            $transaction->rollBack();
525
            if (YII_DEBUG || YII_ENV !== YII_ENV_PROD) {
526
                Yii::error($ex->errorInfo, static::class . '\update');
527
                return $ex;
528
            }
529
            Yii::warning($ex->errorInfo, static::class . '\update');
530
            return false;
531
        }
532 3
        return true;
533
    }
534
535
    /**
536
     * Delete all children, not grandchildren (descendants).
537
     * If onDeleteType is `on cascade`, the children will be deleted automatically.
538
     * If onDeleteType is `on restrict` and contains children, the deletion will
539
     * be restricted.
540
     * @return IntegrityException|boolean true if all delete operations
541
     * succeeded to execute, or false if anyone of them failed. If not production
542
     * environment or enable debug mode, it will return exception.
543
     * @throws IntegrityException throw if anyone delete failed.
544
     * The exception message only contains the first error.
545
     */
546 3
    public function deleteChildren()
547
    {
548 3
        $children = $this->children;
549 3
        if (empty($children)) {
550 3
            return true;
551
        }
552 1
        $transaction = $this->getDb()->beginTransaction();
0 ignored issues
show
Bug introduced by
It seems like getDb() 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...
553
        try {
554 1
            foreach ($children as $child) {
555
                /* @var $child static */
556 1
                if (!$child->delete()) {
0 ignored issues
show
Bug introduced by
The method delete() does not exist on rhosocial\base\models\traits\SelfBlameableTrait. Did you maybe mean onDeleteChildren()?

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...
557 1
                    throw new IntegrityException('Delete failed:', $child->getErrors());
0 ignored issues
show
Bug introduced by
It seems like getErrors() 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...
558
                }
559
            }
560 1
            $transaction->commit();
561
        } catch (IntegrityException $ex) {
562
            $transaction->rollBack();
563
            if (YII_DEBUG || YII_ENV !== YII_ENV_PROD) {
564
                Yii::error($ex->errorInfo, static::class . '\delete');
565
                return $ex;
566
            }
567
            Yii::warning($ex->errorInfo, static::class . '\delete');
568
            return false;
569
        }
570 1
        return true;
571
    }
572
573
    /**
574
     * Update children's parent attribute.
575
     * Event triggered before updating.
576
     * @param ModelEvent $event
577
     * @return boolean
578
     */
579 17
    public function onParentRefIdChanged($event)
580
    {
581 17
        $sender = $event->sender;
582 17
        if ($sender->isAttributeChanged($sender->refIdAttribute)) {
583 4
            return $sender->onUpdateChildren($event);
584
        }
585 16
    }
586
587
    /**
588
     * Attach events associated with self blameable attribute.
589
     */
590 124
    protected function initSelfBlameableEvents()
591
    {
592 124
        $this->on(static::EVENT_BEFORE_UPDATE, [$this, 'onParentRefIdChanged']);
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...
593 124
        $this->on(static::EVENT_BEFORE_DELETE, [$this, 'onDeleteChildren']);
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...
594 124
    }
595
    
596
    /**
597
     * Clear invalid parent.
598
     * The invalid state depends on which if parent id exists but it's corresponding
599
     * parent cannot be found.
600
     * @return boolean True if parent attribute is set null, False if parent valid.
601
     */
602 4
    public function clearInvalidParent()
603
    {
604 4
        if ($this->getParentId() !== static::$nullParent && !$this->hasParent()) {
605 2
            $this->setNullParent();
606 2
            return true;
607
        }
608 2
        return false;
609
    }
610
}
611