Category::__call()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 9.9666
c 0
b 0
f 0
cc 2
nc 2
nop 2
crap 2
1
<?php
2
3
namespace UniSharp\Categorizable\Models;
4
5
use Kalnoy\Nestedset\NodeTrait;
6
use Illuminate\Database\Eloquent\Model;
7
8
class Category extends Model
9
{
10
    use NodeTrait;
11
12
    protected $fillable = ['name', 'parent_id'];
13
14 36
    public static function boot()
15
    {
16 36
        parent::boot();
17
        static::deleting(function ($model) {
18 2
            collect(array_keys(config('categorizable.morphs')))->each(function ($relation) use ($model) {
19 2
                $model->{$relation}()->sync([]);
20 2
            });
21 36
        });
22 36
    }
23
24 4
    public function categorizables($class)
25
    {
26 4
        return $this->morphedByMany($class, 'categorizable', 'categorizable', 'category_id');
27
    }
28
29 22
    public function getRelationValue($key)
30
    {
31 22
        if ($this->relationLoaded($key)) {
32 22
            return $this->relations[$key];
33
        }
34
35
        if (array_key_exists($key, config('categorizable.morphs', []))) {
36
            $class = config('categorizable.morphs')[$key];
37
            $relation = $this->categorizables($class);
38
            return tap($relation->getResults(), function ($results) use ($key) {
39
                $this->setRelation($key, $results);
40
            });
41
        }
42
43
        return parent::getRelationValue($key);
44
    }
45
46
47 36
    public function __call($method, $arguments)
48
    {
49 36
        if (array_key_exists($method, config('categorizable.morphs', []))) {
50 4
            $class = config('categorizable.morphs')[$method];
51 4
            return $this->categorizables($class);
52
        }
53
54 36
        return parent::__call($method, $arguments);
55
    }
56
}
57