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