Completed
Push — master ( b768a2...bedbb4 )
by vistart
05:58
created

SelfBlameableTrait::getAncestorModels()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4.0466

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 11
ccs 6
cts 7
cp 0.8571
rs 9.2
cc 4
eloc 7
nc 3
nop 1
crap 4.0466
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 $onNoAction = 0;
75
    public static $onRestrict = 1;
76
    public static $onCascade = 2;
77
    public static $onSetNull = 3;
78
    public static $onUpdateTypes = [
79
        0 => 'on action',
80
        1 => 'restrict',
81
        2 => 'cascade',
82
        3 => 'set null',
83
    ];
84
85
    /**
86
     * @var integer indicates the on delete type. default to cascade.
87
     */
88
    public $onDeleteType = 2;
89
90
    /**
91
     * @var integer indicates the on update type. default to cascade.
92
     */
93
    public $onUpdateType = 2;
94
95
    /**
96
     * @var boolean indicates whether throw exception or not when restriction occured on updating or deleting operation.
97
     */
98
    public $throwRestrictException = false;
99
    
100
    /**
101
     * @var array store the attribute validation rules.
102
     * If this field is a non-empty array, then it will be given.
103
     */
104
    private $localSelfBlameableRules = [];
105
    public static $eventParentChanged = 'parentChanged';
106
    public static $eventChildAdded = 'childAdded';
107
108
    /**
109
     * @var false|integer Set the limit of ancestor level. False is no limit.
110
     * We strongly recommend you set an unsigned integer which is less than 256.
111
     */
112
    public $ancestorLimit = false;
113
114
    /**
115
     * @var false|integer Set the limit of children (not descendants). False is no limit.
116
     * We strongly recommend you set an unsigned integer which is less than 1024.
117
     */
118
    public $childrenLimit = false;
119
120
    /**
121
     * Get rules associated with self blameable attribute.
122
     * If self-blameable rules has been stored locally, then it will be given,
123
     * or return the parent attribute rule.
124
     * @return array rules.
125
     */
126 107
    public function getSelfBlameableRules()
127
    {
128 107
        if (!is_string($this->parentAttribute)) {
129 107
            return [];
130
        }
131 26
        if (!empty($this->localSelfBlameableRules) && is_array($this->localSelfBlameableRules)) {
132 2
            return $this->localSelfBlameableRules;
133
        }
134 26
        if (is_string($this->parentAttributeRule)) {
135
            $this->parentAttributeRule = [$this->parentAttributeRule];
136
        }
137 26
        $this->localSelfBlameableRules = [
138 26
            array_merge([$this->parentAttribute], $this->parentAttributeRule),
139
        ];
140 26
        return $this->localSelfBlameableRules;
141
    }
142
143
    /**
144
     * Set rules associated with self blameable attribute.
145
     * @param array $rules rules.
146
     */
147 1
    public function setSelfBlameableRules($rules = [])
148
    {
149 1
        $this->localSelfBlameableRules = $rules;
150 1
    }
151
152
    /**
153
     * Check whether this model has reached the ancestor limit.
154
     * If $ancestorLimit is false, it will be regared as no limit(return false).
155
     * If $ancestorLimit is not false and not an unsigned integer, 256 will be taken.
156
     * @return boolean
157
     */
158 35
    public function hasReachedAncestorLimit()
159
    {
160 35
        if ($this->ancestorLimit === false) {
161 35
            return false;
162
        }
163 2
        if (!is_numeric($this->ancestorLimit) || $this->ancestorLimit < 0) {
164 1
            $this->ancestorLimit = 256;
165
        }
166 2
        return count($this->getAncestorChain()) >= $this->ancestorLimit;
167
    }
168
169
    /**
170
     * Check whether this model has reached the children limit.
171
     * If $childrenLimit is false, it will be regarded as no limit(return false).
172
     * If $childrenLimit is not false and not an unsigned integer, 1024 will be taken.
173
     * @return boolean
174
     */
175 3
    public function hasReachedChildrenLimit()
176
    {
177 3
        if ($this->childrenLimit === false) {
178 3
            return false;
179
        }
180 1
        if (!is_numeric($this->childrenLimit) || $this->childrenLimit < 0) {
181 1
            $this->childrenLimit = 1024;
182
        }
183 1
        return ((int) $this->getChildren()->count()) >= $this->childrenLimit;
184
    }
185
186
    /**
187
     * Bear a child.
188
     * The creator of this child is not necessarily the creator of current one.
189
     * For example: Someone commit a comment on another user's comment, these
190
     * two comments are father and son, but do not belong to the same owner.
191
     * Therefore, you need to specify the creator of current model.
192
     * @param array $config
193
     * @return static|null Null if reached the ancestor limit or children limit.
194
     * @throws InvalidConfigException Self reference ID attribute or
195
     * parent attribute not determined.
196
     * @throws InvalidParamException ancestor or children limit reached.
197
     */
198 2
    public function bear($config = [])
199
    {
200 2
        if (!$this->parentAttribute) {
201
            throw new InvalidConfigException("Parent Attribute Not Determined.");
202
        }
203 2
        if (!$this->refIdAttribute) {
204
            throw new InvalidConfigException("Self Reference ID Attribute Not Determined.");
205
        }
206 2
        if ($this->hasReachedAncestorLimit()) {
207
            throw new InvalidParamException("Reached Ancestor Limit: " . $this->ancestorLimit);
208
        }
209 2
        if ($this->hasReachedChildrenLimit()) {
210
            throw new InvalidParamException("Reached Children Limit: ". $this->childrenLimit);
211
        }
212 2
        if (isset($config['class'])) {
213
            unset($config['class']);
214
        }
215 2
        $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...
216 2
        if ($this->addChild($model) === false) {
217
            return false;
218
        }
219 2
        return $model;
220
    }
221
222
    /**
223
     * Add a child.
224
     * @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...
225
     * @return boolean
226
     */
227 2
    public function addChild($child)
228
    {
229 2
        return $this->hasReachedChildrenLimit() ? false : $child->setParent($this);
230
    }
231
232
    /**
233
     * Event triggered before deleting itself.
234
     * @param ModelEvent $event
235
     * @return boolean true if parentAttribute not specified.
236
     * @throws IntegrityException throw if $throwRestrictException is true when $onDeleteType is on restrict.
237
     */
238 51
    public function onDeleteChildren($event)
239
    {
240 51
        $sender = $event->sender;
241
        /* @var @sender static */
242 51
        if (empty($sender->parentAttribute) || !is_string($sender->parentAttribute)) {
243 49
            return true;
244
        }
245 2
        switch ($sender->onDeleteType) {
246 2
            case static::$onRestrict:
247
                $event->isValid = $sender->children === null;
248
                if ($this->throwRestrictException) {
249
                    throw new IntegrityException('Delete restricted.');
250
                }
251
                break;
252 2
            case static::$onCascade:
253 2
                $event->isValid = $sender->deleteChildren();
254 2
                break;
255
            case static::$onSetNull:
256
                $event->isValid = $sender->updateChildren(null);
257
                break;
258
            case static::$onNoAction:
259
            default:
260
                $event->isValid = true;
261
                break;
262
        }
263 2
    }
264
265
    /**
266
     * Event triggered before updating itself.
267
     * @param ModelEvent $event
268
     * @return boolean true if parentAttribute not specified.
269
     * @throws IntegrityException throw if $throwRestrictException is true when $onUpdateType is on restrict.
270
     */
271
    public function onUpdateChildren($event)
272
    {
273
        $sender = $event->sender;
274
        /* @var @sender static */
275
        if (empty($sender->parentAttribute) || !is_string($sender->parentAttribute)) {
276
            return true;
277
        }
278
        switch ($sender->onUpdateType) {
279
            case static::$onRestrict:
280
                $event->isValid = $sender->getOldChildren() === null;
281
                if ($this->throwRestrictException) {
282
                    throw new IntegrityException('Update restricted.');
283
                }
284
                break;
285
            case static::$onCascade:
286
                $event->isValid = $sender->updateChildren();
287
                break;
288
            case static::$onSetNull:
289
                $event->isValid = $sender->updateChildren(null);
290
                break;
291
            case static::$onNoAction:
292
            default:
293
                $event->isValid = true;
294
                break;
295
        }
296
    }
297
298
    /**
299
     * Get parent query.
300
     * Or get parent instance if access by magic property.
301
     * @return ActiveQuery
302
     */
303 35
    public function getParent()
304
    {
305 35
        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...
306
    }
307
308
    /**
309
     * Set parent.
310
     * Don't forget save model after setting it.
311
     * @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...
312
     * @return false|string False if restriction reached. Otherwise parent's GUID given.
313
     */
314 35
    public function setParent($parent)
315
    {
316 35
        if (empty($parent) || $this->getGUID() == $parent->getGUID() || $parent->hasAncestor($this) || $parent->hasReachedAncestorLimit()) {
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...
317
            return false;
318
        }
319 35
        unset($this->parent);
320 35
        unset($parent->children);
321 35
        $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...
322 35
        $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...
323 35
        return $this->{$this->parentAttribute} = $parent->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...
324
    }
325
326
    /**
327
     * Check whether this model has parent.
328
     * @return boolean
329
     */
330 35
    public function hasParent()
331
    {
332 35
        return $this->parent !== null;
333
    }
334
335
    /**
336
     * Check whether if $ancestor is the ancestor of myself.
337
     * Note, Itself will not be regarded as the its ancestor.
338
     * @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...
339
     * @return boolean
340
     */
341 35
    public function hasAncestor($ancestor)
342
    {
343 35
        if (!$this->hasParent()) {
344 35
            return false;
345
        }
346 3
        if ($this->parent->getGUID() == $ancestor->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...
347 1
            return true;
348
        }
349 3
        return $this->parent->hasAncestor($ancestor);
350
    }
351
352
    /**
353
     * Get ancestor chain. (Ancestors' GUID Only!)
354
     * If this model has ancestor, the return array consists all the ancestor in order.
355
     * The first element is parent, and the last element is root, otherwise return empty array.
356
     * If you want to get ancestor model, you can simplify instance a query and specify the
357
     * condition with the return value. But it will not return models under the order of ancestor chain.
358
     * @param string[] $ancestor
359
     * @return string[]
360
     */
361 5
    public function getAncestorChain($ancestor = [])
362
    {
363 5
        if (!is_string($this->parentAttribute)) {
364
            return [];
365
        }
366 5
        if (!$this->hasParent()) {
367 5
            return $ancestor;
368
        }
369 5
        $ancestor[] = $this->parent->getGUID();
370 5
        return $this->parent->getAncestorChain($ancestor);
371
    }
372
373
    /**
374
     * Get ancestors with specified ancestor chain.
375
     * @param string[] $ancestor Ancestor chain.
376
     * @return static[]|null
377
     */
378 2
    public static function getAncestorModels($ancestor)
379
    {
380 2
        if (empty($ancestor) || !is_array($ancestor)) {
381
            return null;
382
        }
383 2
        $models = [];
384 2
        foreach ($ancestor as $self) {
385 2
            $models[] = static::findOne($self);
386
        }
387 2
        return $models;
388
    }
389
390
    /**
391
     * Get ancestors.
392
     * @return static[]|null
393
     */
394 1
    public function getAncestors()
395
    {
396 1
        return (is_string($this->parentAttribute) && !empty($this->parentAttribute)) ?
397 1
        static::getAncestorModels($this->getAncestorChain()) : null;
398
    }
399
400
    /**
401
     * Check whether if this model has common ancestor with $model.
402
     * @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...
403
     * @return boolean
404
     */
405 1
    public function hasCommonAncestor($model)
406
    {
407 1
        return $this->getCommonAncestor($model) !== null;
408
    }
409
410
    /**
411
     * Get common ancestor. If there isn't common ancestor, null will be given.
412
     * @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...
413
     * @return static
414
     */
415 1
    public function getCommonAncestor($model)
416
    {
417 1
        if (empty($this->parentAttribute) || !is_string($this->parentAttribute) || empty($model) || !$model->hasParent()) {
418
            return null;
419
        }
420 1
        $ancestor = $this->getAncestorChain();
421 1
        if (in_array($model->parent->getGUID(), $ancestor)) {
422 1
            return $model->parent;
423
        }
424
        return $this->getCommonAncestor($model->parent);
425
    }
426
427
    /**
428
     * Get children query.
429
     * Or get children instances if access magic property.
430
     * @return ActiveQuery
431
     */
432 35
    public function getChildren()
433
    {
434 35
        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...
435
    }
436
437
    /**
438
     * Get children which parent attribute point to old guid.
439
     * @return static[]
440
     */
441
    public function getOldChildren()
442
    {
443
        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...
444
    }
445
446
    /**
447
     * Update all children, not grandchildren (descendants).
448
     * If onUpdateType is on cascade, the children will be updated automatically.
449
     * @param mixed $value set guid if false, set empty string if empty() return
450
     * true, otherwise set it to $parentAttribute.
451
     * @return IntegrityException|boolean true if all update operations
452
     * succeeded to execute, or false if anyone of them failed. If not production
453
     * environment or enable debug mode, it will return exception.
454
     * @throws IntegrityException throw if anyone update failed.
455
     * The exception message only contains the first error.
456
     */
457
    public function updateChildren($value = false)
458
    {
459
        $children = $this->getOldChildren();
460
        if (empty($children)) {
461
            return true;
462
        }
463
        $parentAttribute = $this->parentAttribute;
464
        $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...
465
        try {
466
            foreach ($children as $child) {
467
                if ($value === false) {
468
                    $refIdAttribute = $this->refIdAttribute;
469
                    $child->$parentAttribute = $this->$refIdAttribute;
470
                } elseif (empty($value)) {
471
                    $child->$parentAttribute = '';
472
                } else {
473
                    $child->$parentAttribute = $value;
474
                }
475
                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...
476
                    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...
477
                }
478
            }
479
            $transaction->commit();
480
        } catch (IntegrityException $ex) {
481
            $transaction->rollBack();
482
            if (YII_DEBUG || YII_ENV !== YII_ENV_PROD) {
483
                Yii::error($ex->errorInfo, static::class . '\update');
484
                return $ex;
485
            }
486
            Yii::warning($ex->errorInfo, static::class . '\update');
487
            return false;
488
        }
489
        return true;
490
    }
491
492
    /**
493
     * Delete all children, not grandchildren (descendants).
494
     * If onDeleteType is `on cascade`, the children will be deleted automatically.
495
     * If onDeleteType is `on restrict` and contains children, the deletion will
496
     * be restricted.
497
     * @return IntegrityException|boolean true if all delete operations
498
     * succeeded to execute, or false if anyone of them failed. If not production
499
     * environment or enable debug mode, it will return exception.
500
     * @throws IntegrityException throw if anyone delete failed.
501
     * The exception message only contains the first error.
502
     */
503 2
    public function deleteChildren()
504
    {
505 2
        $children = $this->children;
506 2
        if (empty($children)) {
507 2
            return true;
508
        }
509
        $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...
510
        try {
511
            foreach ($children as $child) {
512
                if (!$child->delete()) {
513
                    throw new IntegrityException('Delete failed:', $child->getErrors());
514
                }
515
            }
516
            $transaction->commit();
517
        } catch (IntegrityException $ex) {
518
            $transaction->rollBack();
519
            if (YII_DEBUG || YII_ENV !== YII_ENV_PROD) {
520
                Yii::error($ex->errorInfo, static::class . '\delete');
521
                return $ex;
522
            }
523
            Yii::warning($ex->errorInfo, static::class . '\delete');
524
            return false;
525
        }
526
        return true;
527
    }
528
529
    /**
530
     * Update children's parent attribute.
531
     * Event triggered before updating.
532
     * @param ModelEvent $event
533
     * @return boolean
534
     */
535 11
    public function onParentRefIdChanged($event)
536
    {
537 11
        $sender = $event->sender;
538 11
        if ($sender->isAttributeChanged($sender->refIdAttribute)) {
539
            return $sender->onUpdateChildren($event);
540
        }
541 11
    }
542
543
    /**
544
     * Attach events associated with self blameable attribute.
545
     */
546 113
    protected function initSelfBlameableEvents()
547
    {
548 113
        $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...
549 113
        $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...
550 113
    }
551
}
552