-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAbstractFilterableRepository.php
80 lines (59 loc) · 1.68 KB
/
AbstractFilterableRepository.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
declare(strict_types=1);
namespace DevMakerLab\LaravelFilters;
use Illuminate\Database\Query\Builder;
abstract class AbstractFilterableRepository
{
protected array $filters = [];
protected ?int $limit = null;
/**
* @throws FilterClassNotFound
* @throws IncorrectFilterException
*/
public function addFilter(string $filter): self
{
if (! class_exists($filter)) {
throw new FilterClassNotFound();
}
if (! is_subclass_of($filter, AbstractFilter::class)) {
throw new IncorrectFilterException($filter);
}
$this->filters[] = $filter;
return $this;
}
public function resetFilters(): self
{
$this->filters = [];
return $this;
}
public function limit(int $limit): self
{
$this->limit = $limit;
return $this;
}
public function resetLimit(): self
{
$this->limit = null;
return $this;
}
public function applyFilters(Builder &$builder, array $args): self
{
foreach ($this->filters as $filter) {
$neededArgs = $this->extractNeededArgs($filter, $args);
if ($filter::isApplicable($neededArgs)) {
$filterInstance = new $filter($neededArgs);
$filterInstance->apply($builder);
}
}
if ($this->limit) {
$builder->limit($this->limit);
}
$this->resetFilters();
$this->resetLimit();
return $this;
}
private function extractNeededArgs(string $class, array $args): array
{
return array_intersect_key($args, array_flip(array_keys(get_class_vars($class))));
}
}