Completed
Push — master ( 76c9ed...47b819 )
by vistart
10:25 queued 04:16
created

SelfBlameableTrait::setSelfBlameableRules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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 yii\base\ModelEvent;
16
use yii\db\ActiveQuery;
17
use yii\db\IntegrityException;
18
19
/**
20
 * Description of SelfBlameableTrait
21
 *
22
 * @property static $parent
23
 * @property-read static[] $children
24
 * @property-read static[] $oldChildren
25
 * @property array $selfBlameableRules
26
 * @version 2.0
27
 * @author vistart <[email protected]>
28
 */
29
trait SelfBlameableTrait
30
{
31
32
    /**
33
     * @var false|string attribute name of which store the parent's guid.
34
     */
35
    public $parentAttribute = false;
36
37
    /**
38
     * @var string|array rule name and parameters of parent attribute, as well
39
     * as self referenced ID attribute.
40
     */
41
    public $parentAttributeRule = ['string', 'max' => 36];
42
43
    /**
44
     * @var string self referenced ID attribute.
45
     */
46
    public $refIdAttribute = 'guid';
47
    public static $parentNone = 0;
48
    public static $parentParent = 1;
49
    public static $parentTypes = [
50
        0 => 'none',
51
        1 => 'parent',
52
    ];
53
    public static $onNoAction = 0;
54
    public static $onRestrict = 1;
55
    public static $onCascade = 2;
56
    public static $onSetNull = 3;
57
    public static $onUpdateTypes = [
58
        0 => 'on action',
59
        1 => 'restrict',
60
        2 => 'cascade',
61
        3 => 'set null',
62
    ];
63
64
    /**
65
     * @var integer indicates the on delete type. default to cascade.
66
     */
67
    public $onDeleteType = 2;
68
69
    /**
70
     * @var integer indicates the on update type. default to cascade.
71
     */
72
    public $onUpdateType = 2;
73
74
    /**
75
     * @var boolean indicates whether throw exception or not when restriction occured on updating or deleting operation.
76
     */
77
    public $throwRestrictException = false;
78
    private $localSelfBlameableRules = [];
79
    public static $eventParentChanged = 'parentChanged';
80
81
    /**
82
     * Get rules associated with self blameable attribute.
83
     * @return array rules.
84
     */
85 13
    public function getSelfBlameableRules()
86
    {
87 13
        if (!is_string($this->parentAttribute)) {
88 12
            return [];
89
        }
90 1
        if (!empty($this->localSelfBlameableRules) && is_array($this->localSelfBlameableRules)) {
91 1
            return $this->localSelfBlameableRules;
92
        }
93 1
        if (is_string($this->parentAttributeRule)) {
94
            $this->parentAttributeRule = [$this->parentAttributeRule];
95
        }
96 1
        $this->localSelfBlameableRules = [
97 1
            array_merge([$this->parentAttribute], $this->parentAttributeRule),
98
        ];
99 1
        return $this->localSelfBlameableRules;
100
    }
101
102
    /**
103
     * Set rules associated with self blameable attribute.
104
     * @param array $rules rules.
105
     */
106 1
    public function setSelfBlameableRules($rules = [])
107
    {
108 1
        $this->localSelfBlameableRules = $rules;
109 1
    }
110
111
    /**
112
     * Bear a child.
113
     * @param array $config
114
     * @return static
115
     */
116 10
    public function bear($config = [])
117
    {
118 10
        if (isset($config['class'])) {
119 10
            unset($config['class']);
120 10
        }
121 10
        $refIdAttribute = $this->refIdAttribute;
122 10
        $config[$this->parentAttribute] = $this->$refIdAttribute;
123 10
        return 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...
124
    }
125
126
    /**
127
     * Event triggered before deleting itself.
128
     * @param ModelEvent $event
129
     * @return boolean true if parentAttribute not specified.
130
     * @throws IntegrityException throw if $throwRestrictException is true when $onDeleteType is on restrict.
131
     */
132 19
    public function onDeleteChildren($event)
133
    {
134 19
        $sender = $event->sender;
135 19
        if (!is_string($sender->parentAttribute)) {
136 15
            return true;
137
        }
138 4
        switch ($sender->onDeleteType) {
139 4
            case static::$onRestrict:
140 1
                $event->isValid = $sender->children === null;
141 1
                if ($this->throwRestrictException) {
142 1
                    throw new \yii\db\IntegrityException('Delete restricted.');
143
                }
144 1
                break;
145 3
            case static::$onCascade:
146 1
                $event->isValid = $sender->deleteChildren();
147 1
                break;
148 2
            case static::$onSetNull:
149 1
                $event->isValid = $sender->updateChildren(null);
150 1
                break;
151 1
            case static::$onNoAction:
152 1
            default:
153 1
                $event->isValid = true;
154 1
                break;
155 4
        }
156 4
    }
157
158
    /**
159
     * Event triggered before updating itself.
160
     * @param ModelEvent $event
161
     * @return boolean true if parentAttribute not specified.
162
     * @throws IntegrityException throw if $throwRestrictException is true when $onUpdateType is on restrict.
163
     */
164 4
    public function onUpdateChildren($event)
165
    {
166 4
        $sender = $event->sender;
167 4
        if (!is_string($sender->parentAttribute)) {
168
            return true;
169
        }
170 4
        switch ($sender->onUpdateType) {
171 4
            case static::$onRestrict:
172 1
                $event->isValid = $sender->getOldChildren() === null;
173 1
                if ($this->throwRestrictException) {
174 1
                    throw new \yii\db\IntegrityException('Update restricted.');
175
                }
176
                break;
177 3
            case static::$onCascade:
178 1
                $event->isValid = $sender->updateChildren();
179 1
                break;
180 2
            case static::$onSetNull:
181 1
                $event->isValid = $sender->updateChildren(null);
182 1
                break;
183 1
            case static::$onNoAction:
184 1
            default:
185 1
                $event->isValid = true;
186 1
                break;
187 3
        }
188 3
    }
189
190
    /**
191
     * Get parent query.
192
     * Or get parent instance if access by magic property.
193
     * @return ActiveQuery
194
     */
195 3
    public function getParent()
196
    {
197 3
        return $this->hasOne(static::className(), [$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...
198
    }
199
200
    /**
201
     * Set parent.
202
     * Don't forget save model after setting it.
203
     * @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...
204
     * @return false|string
205
     */
206 1
    public function setParent($parent)
207
    {
208 1
        if (empty($parent) || $this->guid == $parent->guid || $parent->hasAncestor($this)) {
0 ignored issues
show
Bug introduced by
The property guid 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...
209
            return false;
210
        }
211 1
        unset($this->parent);
212 1
        $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...
213 1
        return $this->{$this->parentAttribute} = $parent->guid;
214
    }
215
216
    /**
217
     * Check whether this model has parent.
218
     * @return boolean
219
     */
220 1
    public function hasParent()
221
    {
222 1
        return $this->parent !== null;
223
    }
224
225 1
    public function hasAncestor($ancestor)
226
    {
227 1
        if ($this->guid == $ancestor->guid) {
228
            return true;
229
        }
230 1
        if (!$this->hasParent()) {
231 1
            return false;
232
        }
233 1
        return $this->parent->hasAncestor($ancestor);
234
    }
235
236
    /**
237
     * Get ancestor chain. (Ancestor GUID Only!)
238
     * If this model has ancestor, the return array consists all the ancestor in order.
239
     * The first element is parent, and the last element is root, otherwise return empty array.
240
     * If you want to get ancestor model, you can simplify instance a query and specify the 
241
     * condition with the return value. But it will not return models under the order of ancestor chain.
242
     * @param string[] $ancestor
243
     * @return string[]
244
     */
245 1
    public function getAncestorChain($ancestor = [])
246
    {
247 1
        if (!is_string($this->parentAttribute)) {
248
            return [];
249
        }
250 1
        if (!$this->hasParent()) {
251 1
            return $ancestor;
252
        }
253 1
        $ancestor[] = $this->parent->guid;
254 1
        return $this->parent->getAncestorChain($ancestor);
255
    }
256
257
    /**
258
     * Get ancestors with specified ancestor chain.
259
     * @param string[] $ancestor Ancestor chain.
260
     * @return static[]|null
261
     */
262 1
    public static function getAncestorModels($ancestor)
263
    {
264 1
        if (empty($ancestor) || !is_array($ancestor)) {
265 1
            return null;
266
        }
267 1
        $models = [];
268 1
        foreach ($ancestor as $self) {
269 1
            $models[] = static::findOne($self);
270 1
        }
271 1
        return $models;
272
    }
273
274
    /**
275
     * Get ancestors.
276
     * @return static[]|null
277
     */
278 1
    public function getAncestors()
279
    {
280 1
        return is_string($this->parentAttribute) ? $this->getAncestorModels($this->getAncestorChain()) : null;
281
    }
282
283
    /**
284
     * Get children query.
285
     * Or get children instances if access magic property.
286
     * @return ActiveQuery
287
     */
288 3
    public function getChildren()
289
    {
290 3
        return $this->hasMany(static::className(), [$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...
291
    }
292
293
    /**
294
     * Get children which parent attribute point to the my old guid.
295
     * @return static[]
296
     */
297 4
    public function getOldChildren()
298
    {
299 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...
300
    }
301
302
    /**
303
     * Update all children, not grandchildren.
304
     * If onUpdateType is on cascade, the children will be updated automatically.
305
     * @param mixed $value set guid if false, set empty string if empty() return
306
     * true, otherwise set it to $parentAttribute.
307
     * @return IntegrityException|boolean true if all update operations
308
     * succeeded to execute, or false if anyone of them failed. If not production
309
     * environment or enable debug mode, it will return exception.
310
     * @throws IntegrityException throw if anyone update failed.
311
     */
312 3
    public function updateChildren($value = false)
313
    {
314 3
        $children = $this->getOldChildren();
315 3
        if (empty($children)) {
316
            return true;
317
        }
318 3
        $parentAttribute = $this->parentAttribute;
319 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...
320
        try {
321 3
            foreach ($children as $child) {
322 3
                if ($value === false) {
323 1
                    $refIdAttribute = $this->refIdAttribute;
324 1
                    $child->$parentAttribute = $this->$refIdAttribute;
325 3
                } elseif (empty($value)) {
326 2
                    $child->$parentAttribute = '';
327 2
                } else {
328
                    $child->$parentAttribute = $value;
329
                }
330 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...
331
                    throw new \yii\db\IntegrityException('Update failed:' . $child->errors);
0 ignored issues
show
Bug introduced by
The property errors 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...
332
                }
333 3
            }
334 3
            $transaction->commit();
335 3
        } catch (\yii\db\IntegrityException $ex) {
336
            $transaction->rollBack();
337
            if (YII_DEBUG || YII_ENV !== YII_ENV_PROD) {
338
                Yii::error($ex->errorInfo, static::className() . '\update');
339
                return $ex;
340
            }
341
            Yii::warning($ex->errorInfo, static::className() . '\update');
342
            return false;
343
        }
344 3
        return true;
345
    }
346
347
    /**
348
     * Delete all children, not grandchildren.
349
     * If onDeleteType is on cascade, the children will be deleted automatically.
350
     * If onDeleteType is on restrict and contains children, the deletion will
351
     * be restricted.
352
     * @return IntegrityException|boolean true if all delete operations
353
     * succeeded to execute, or false if anyone of them failed. If not production
354
     * environment or enable debug mode, it will return exception.
355
     * @throws IntegrityException throw if anyone delete failed.
356
     */
357 1
    public function deleteChildren()
358
    {
359 1
        $children = $this->children;
360 1
        if (empty($children)) {
361 1
            return true;
362
        }
363 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...
364
        try {
365 1
            foreach ($children as $child) {
366 1
                if (!$child->delete()) {
367
                    throw new \yii\db\IntegrityException('Delete failed:' . $child->errors);
368
                }
369 1
            }
370 1
            $transaction->commit();
371 1
        } catch (\yii\db\IntegrityException $ex) {
372
            $transaction->rollBack();
373
            if (YII_DEBUG || YII_ENV !== YII_ENV_PROD) {
374
                Yii::error($ex->errorInfo, static::className() . '\delete');
375
                return $ex;
376
            }
377
            Yii::warning($ex->errorInfo, static::className() . '\delete');
378
            return false;
379
        }
380 1
        return true;
381
    }
382
383
    /**
384
     * Update children's parent attribute.
385
     * Event triggered before updating.
386
     * @param ModelEvent $event
387
     * @return boolean
388
     */
389 16
    public function onParentRefIdChanged($event)
390
    {
391 16
        $sender = $event->sender;
392 16
        if ($sender->isAttributeChanged($sender->refIdAttribute)) {
393 4
            return $sender->onUpdateChildren($event);
394
        }
395 14
    }
396
397 38
    protected function initSelfBlameableEvents()
398
    {
399 38
        $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...
400 38
        $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...
401 38
    }
402
403
    /**
404
     * Check whether if this model has common ancestor with $model.
405
     * @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...
406
     * @return boolean
407
     */
408 1
    public function hasCommonAncestor($model)
409
    {
410 1
        return is_string($this->parentAttribute) ? $this->getCommonAncestor($model) !== null : false;
411
    }
412
413
    /**
414
     * Get common ancestor. If there isn't common ancestor, null will be given.
415
     * @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...
416
     * @return static
417
     */
418 1
    public function getCommonAncestor($model)
419
    {
420 1
        if (!is_string($this->parentAttribute) || empty($model) || !$model->hasParent()) {
421 1
            return null;
422
        }
423 1
        $ancestor = $this->getAncestorChain();
424 1
        if (in_array($model->parent->guid, $ancestor)) {
425 1
            return $model->parent;
426
        }
427 1
        return $this->getCommonAncestor($model->parent);
428
    }
429
}
430