|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\QueryBuilder; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Builder; |
|
6
|
|
|
use Spatie\QueryBuilder\Filters\FiltersExact; |
|
7
|
|
|
use Spatie\QueryBuilder\Filters\FiltersScope; |
|
8
|
|
|
use Spatie\QueryBuilder\Filters\FiltersPartial; |
|
9
|
|
|
use Spatie\QueryBuilder\Filters\Filter as CustomFilter; |
|
10
|
|
|
|
|
11
|
|
|
class Filter |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var string */ |
|
14
|
|
|
protected $filterClass; |
|
15
|
|
|
|
|
16
|
|
|
/** @var string */ |
|
17
|
|
|
protected $property; |
|
18
|
|
|
|
|
19
|
|
|
/** @var array */ |
|
20
|
|
|
protected $ignorableValues = []; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct(string $property, $filterClass) |
|
23
|
|
|
{ |
|
24
|
|
|
$this->property = $property; |
|
25
|
|
|
$this->filterClass = $filterClass; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
public function filter(Builder $builder, $value) |
|
29
|
|
|
{ |
|
30
|
|
|
if ($this->shouldBeIgnored($value)) { |
|
31
|
|
|
return; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
$filterClass = $this->resolveFilterClass(); |
|
35
|
|
|
|
|
36
|
|
|
($filterClass)($builder, $value, $this->property); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
public static function exact(string $property) : self |
|
40
|
|
|
{ |
|
41
|
|
|
return new static($property, FiltersExact::class); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
public static function partial(string $property) : self |
|
45
|
|
|
{ |
|
46
|
|
|
return new static($property, FiltersPartial::class); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
public static function scope(string $property) : self |
|
50
|
|
|
{ |
|
51
|
|
|
return new static($property, FiltersScope::class); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
public static function custom(string $property, $filterClass) : self |
|
55
|
|
|
{ |
|
56
|
|
|
return new static($property, $filterClass); |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
|
|
public function getProperty(): string |
|
60
|
|
|
{ |
|
61
|
|
|
return $this->property; |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
public function isForProperty(string $property): bool |
|
65
|
|
|
{ |
|
66
|
|
|
return $this->property === $property; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
public function ignore($values) : self |
|
70
|
|
|
{ |
|
71
|
|
|
$this->ignorableValues = array_merge( |
|
72
|
|
|
$this->ignorableValues, |
|
73
|
|
|
is_array($values) ? $values : func_get_args() |
|
74
|
|
|
); |
|
75
|
|
|
|
|
76
|
|
|
return $this: |
|
|
|
|
|
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
protected function shouldBeIgnored($value) |
|
80
|
|
|
{ |
|
81
|
|
|
return in_array($value, $this->ignorableValues); |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
private function resolveFilterClass(): CustomFilter |
|
85
|
|
|
{ |
|
86
|
|
|
if ($this->filterClass instanceof CustomFilter) { |
|
87
|
|
|
return $this->filterClass; |
|
88
|
|
|
} |
|
89
|
|
|
|
|
90
|
|
|
return new $this->filterClass; |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|