|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace DevMakerLab\LaravelFilters; |
|
6
|
|
|
|
|
7
|
|
|
use Illuminate\Database\Query\Builder; |
|
8
|
|
|
|
|
9
|
|
|
abstract class AbstractFilterableRepository |
|
10
|
|
|
{ |
|
11
|
|
|
protected array $filters = []; |
|
12
|
|
|
|
|
13
|
|
|
protected ?int $limit = null; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* @throws FilterClassNotFound |
|
17
|
|
|
* @throws IncorrectFilterException |
|
18
|
|
|
*/ |
|
19
|
5 |
|
public function addFilter(string $filter): self |
|
20
|
|
|
{ |
|
21
|
5 |
|
if (! class_exists($filter)) { |
|
22
|
1 |
|
throw new FilterClassNotFound(); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
4 |
|
if (! is_subclass_of($filter, AbstractFilter::class)) { |
|
26
|
1 |
|
throw new IncorrectFilterException($filter); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
3 |
|
$this->filters[] = $filter; |
|
30
|
|
|
|
|
31
|
3 |
|
return $this; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
2 |
|
public function resetFilters(): self |
|
35
|
|
|
{ |
|
36
|
2 |
|
$this->filters = []; |
|
37
|
|
|
|
|
38
|
2 |
|
return $this; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
3 |
|
public function limit(int $limit): self |
|
42
|
|
|
{ |
|
43
|
3 |
|
$this->limit = $limit; |
|
44
|
|
|
|
|
45
|
3 |
|
return $this; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
2 |
|
public function resetLimit(): self |
|
49
|
|
|
{ |
|
50
|
2 |
|
$this->limit = null; |
|
51
|
|
|
|
|
52
|
2 |
|
return $this; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
1 |
|
public function applyFilters(Builder &$builder, array $args): self |
|
56
|
|
|
{ |
|
57
|
1 |
|
foreach ($this->filters as $filter) { |
|
58
|
1 |
|
$neededArgs = $this->extractNeededArgs($filter, $args); |
|
59
|
|
|
|
|
60
|
1 |
|
if ($filter::isApplicable($neededArgs)) { |
|
61
|
1 |
|
$filterInstance = new $filter($neededArgs); |
|
62
|
1 |
|
$filterInstance->apply($builder); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
1 |
|
if ($this->limit) { |
|
|
|
|
|
|
67
|
1 |
|
$builder->limit($this->limit); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
1 |
|
$this->resetFilters(); |
|
71
|
1 |
|
$this->resetLimit(); |
|
72
|
|
|
|
|
73
|
1 |
|
return $this; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
1 |
|
private function extractNeededArgs(string $class, array $args): array |
|
77
|
|
|
{ |
|
78
|
1 |
|
return array_intersect_key($args, array_flip(array_keys(get_class_vars($class)))); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|
In PHP, under loose comparison (like
==, or!=, orswitchconditions), values of different types might be equal.For
integervalues, zero is a special case, in particular the following results might be unexpected: