Builder   A
last analyzed

Complexity

Total Complexity 8

Size/Duplication

Total Lines 98
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 17
dl 0
loc 98
rs 10
c 0
b 0
f 0
wmc 8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A getQuery() 0 3 1
A results() 0 7 2
A getModel() 0 3 1
A __call() 0 7 2
A setModel() 0 5 1
A collectModels() 0 7 1
1
<?php
2
3
namespace Silk\Query;
4
5
use Silk\Type\Model;
6
use Silk\Support\Collection;
7
8
abstract class Builder
9
{
10
    /**
11
     * The query instance
12
     * @var object  The query instance
13
     */
14
    protected $query;
15
16
    /**
17
     * @var Model|null  The model instance if set, otherwise null
18
     */
19
    protected $model;
20
21
    /**
22
     * Execute the query and return the raw results.
23
     *
24
     * @return array
25
     */
26
    abstract protected function query();
27
28
    /**
29
     * Get the results as a collection
30
     *
31
     * @return Collection
32
     */
33
    public function results()
34
    {
35
        if ($this->model) {
36
            return $this->collectModels();
37
        }
38
39
        return new Collection($this->query());
40
    }
41
42
    /**
43
     * Get the results as a collection of model instances.
44
     *
45
     * @return Collection
46
     */
47
    protected function collectModels()
48
    {
49
        $modelClass = get_class($this->model);
50
51
        return Collection::make($this->query())
52
                         ->map(function ($result) use ($modelClass) {
53
                             return new $modelClass($result);
54
                         });
55
    }
56
57
    /**
58
     * Set the model for this query.
59
     *
60
     * @param Model $model
61
     *
62
     * @return $this
63
     */
64
    public function setModel(Model $model)
65
    {
66
        $this->model = $model;
67
68
        return $this;
69
    }
70
71
    /**
72
     * Get the model
73
     *
74
     * @return Model
75
     */
76
    public function getModel()
77
    {
78
        return $this->model;
79
    }
80
81
    /**
82
     * Get the query object.
83
     *
84
     * @return object
85
     */
86
    public function getQuery()
87
    {
88
        return $this->query;
89
    }
90
91
    /**
92
     * Handle dynamic method calls on the builder.
93
     *
94
     * @param string $name      Method name
95
     * @param array  $arguments
96
     *
97
     * @return mixed
98
     */
99
    public function __call($name, $arguments)
100
    {
101
        if (method_exists($this->model, 'scope' . ucfirst($name))) {
102
            return $this->model->{'scope' . ucfirst($name)}($this, ...$arguments);
103
        }
104
105
        throw new \BadMethodCallException("No '$name' method exists on " . static::class);
106
    }
107
}
108