Test Failed
Pull Request — master (#13)
by Rail
04:55
created

DynamicRelations::has_many_through()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 7
crap 1
1
<?php
2
3
namespace Imanghafoori\Relativity;
4
5
trait DynamicRelations
6
{
7
    use BaseEloquentOverrides;
8
9
    protected static $methodAllowed = [
10
        'getDynamicRelations',
11
        'hasDynamicRelation',
12
        'removeRelation',
13
        'defineRelation',
14
        'morphed_by_many',
15
        'has_many',
16
        'has_one',
17
        'belongs_to',
18
        'belongs_to_many',
19
        'morph_to_many',
20
        'morph_many',
21
        'morph_one',
22
        'morph_to',
23
        'has_many_through'
24
    ];
25
26
    /**
27
     * @var RelationStore
28
     */
29
    protected static $dynamicRelations;
30
31 9
    public static function bootDynamicRelations()
32
    {
33 9
        static::$dynamicRelations = new RelationStore();
34 9
    }
35
36
    /**
37
     * Dynamically handle calls to the class.
38
     *
39
     * @param  string  $method
40
     * @param  array   $parameters
41
     * @return mixed
42
     *
43
     * @throws \BadMethodCallException
44
     */
45 9
    public function __call($method, $parameters)
46
    {
47
        // Handle internal calls
48 9
        if (in_array($method, static::$methodAllowed)) {
49 9
            $manager = new RelationManager(static::$dynamicRelations);
50
51 9
            return $manager->$method(...array_merge([$this], $parameters));
52
        }
53
54
        // Handle relationships
55 7
        $dynamicRelation = static::$dynamicRelations->get($this, $method);
56
57 7
        if ($dynamicRelation) {
58 6
            return call_user_func_array($dynamicRelation->bindTo($this, static::class), $parameters);
59
        }
60
        
61 7
        return parent::__call($method, $parameters);
62
    }
63
64
    /**
65
     * Convert static call to
66
     *
67
     * @param  string  $method
68
     * @param  array   $parameters
69
     * @return mixed
70
     *
71
     * @throws \BadMethodCallException
72
     */
73 9
    public static function __callStatic($method, $parameters)
74
    {
75 9
        if (in_array($method, static::$methodAllowed)) {
76 9
            $entity = new static;
77 9
            return $entity->$method(...$parameters);
78
        } else {
79 7
            return parent::__callStatic($method, $parameters);
80
        }
81
    }
82
  
83
84 1
    public static function forceEagerLoading(...$relation)
85
    {
86
        static::registerModelEvent('booting', function ($model) use ($relation) {
87
            $model->with = $model->with + $relation;
88 1
        });
89 1
    }
90
}
91