1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Cerbero\QueryFilters; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Builder; |
6
|
|
|
use Illuminate\Http\Request; |
7
|
|
|
use Illuminate\Support\Str; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Abstract implementation of a query filters applier. |
11
|
|
|
* |
12
|
|
|
*/ |
13
|
|
|
abstract class QueryFilters |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* The current HTTP request. |
17
|
|
|
* |
18
|
|
|
* @var Illuminate\Http\Request |
19
|
|
|
*/ |
20
|
|
|
protected $request; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* Eloquent query builder. |
24
|
|
|
* |
25
|
|
|
* @var Illuminate\Database\Eloquent\Builder |
26
|
|
|
*/ |
27
|
|
|
protected $query; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* List of filters not requiring a value. |
31
|
|
|
* |
32
|
|
|
* @var array |
33
|
|
|
*/ |
34
|
|
|
protected $implicitFilters = []; |
35
|
6 |
|
|
36
|
|
|
/** |
37
|
6 |
|
* Set the dependencies. |
38
|
6 |
|
* |
39
|
|
|
* @param Request $request |
40
|
|
|
* @return void |
|
|
|
|
41
|
|
|
*/ |
42
|
|
|
public function __construct(Request $request) |
|
|
|
|
43
|
|
|
{ |
44
|
|
|
$this->request = $request; |
|
|
|
|
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
/** |
48
|
|
|
* Hydrate the filters from plain array. |
49
|
|
|
* |
50
|
|
|
* @param array $queries |
51
|
|
|
* @return static |
52
|
|
|
*/ |
53
|
|
|
public static function hydrate(array $queries) |
54
|
|
|
{ |
55
|
|
|
$request = new Request($queries); |
56
|
|
|
|
57
|
|
|
return new static($request); |
58
|
|
|
} |
59
|
3 |
|
|
60
|
|
|
/** |
61
|
3 |
|
* Apply all the filters to the given query. |
62
|
|
|
* |
63
|
3 |
|
* @param Illuminate\Database\Eloquent\Builder $query |
64
|
3 |
|
* @return Illuminate\Database\Eloquent\Builder |
65
|
|
|
*/ |
66
|
3 |
|
public function applyToQuery(Builder $query) |
67
|
3 |
|
{ |
68
|
3 |
|
$this->query = $query; |
|
|
|
|
69
|
3 |
|
|
70
|
|
|
foreach ($this->request->all() as $filter => $value) { |
71
|
3 |
|
$method = Str::camel($filter); |
72
|
|
|
|
73
|
|
|
if ($this->filterCanBeApplied($method, $value)) { |
74
|
|
|
call_user_func([$this, $method], $value); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return $query; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* Determine whether the given filter can be applied with the provided value. |
83
|
|
|
* |
84
|
|
|
* @param string $filter |
85
|
|
|
* @param mixed $value |
86
|
|
|
* @return boolean |
87
|
|
|
*/ |
88
|
|
|
protected function filterCanBeApplied($filter, $value) |
89
|
|
|
{ |
90
|
|
|
$filterExists = method_exists($this, $filter); |
91
|
|
|
$valueIsLegit = $value !== '' || in_array($filter, $this->implicitFilters); |
92
|
|
|
|
93
|
|
|
return $filterExists && $valueIsLegit; |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|
Adding a
@return
annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.Please refer to the PHP core documentation on constructors.