|
| 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 | + public function addFilter(string $filter): self |
| 20 | + { |
| 21 | + if (! class_exists($filter)) { |
| 22 | + throw new FilterClassNotFound(); |
| 23 | + } |
| 24 | + |
| 25 | + if (! is_subclass_of($filter, FilterInterface::class)) { |
| 26 | + throw new IncorrectFilterException($filter); |
| 27 | + } |
| 28 | + |
| 29 | + $this->filters[] = $filter; |
| 30 | + |
| 31 | + return $this; |
| 32 | + } |
| 33 | + |
| 34 | + public function resetFilters(): self |
| 35 | + { |
| 36 | + $this->filters = []; |
| 37 | + |
| 38 | + return $this; |
| 39 | + } |
| 40 | + |
| 41 | + public function limit(int $limit): self |
| 42 | + { |
| 43 | + $this->limit = $limit; |
| 44 | + |
| 45 | + return $this; |
| 46 | + } |
| 47 | + |
| 48 | + public function resetLimit(): self |
| 49 | + { |
| 50 | + $this->limit = null; |
| 51 | + |
| 52 | + return $this; |
| 53 | + } |
| 54 | + |
| 55 | + public function applyFilters(Builder &$builder, array $args): self |
| 56 | + { |
| 57 | + foreach ($this->filters as $filter) { |
| 58 | + $neededKeys = $filter::neededKeys(); |
| 59 | + $neededArgs = $this->extractNeededArgs($neededKeys, $args); |
| 60 | + |
| 61 | + if ($filter::isApplicable($neededArgs)) { |
| 62 | + (new $filter)->apply($builder, $neededArgs); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + if ($this->limit) { |
| 67 | + $builder->limit($this->limit); |
| 68 | + } |
| 69 | + |
| 70 | + $this->resetFilters(); |
| 71 | + $this->resetLimit(); |
| 72 | + |
| 73 | + return $this; |
| 74 | + } |
| 75 | + |
| 76 | + private function extractNeededArgs(array $neededKeys, array $args): array |
| 77 | + { |
| 78 | + return array_intersect_key($args, array_flip($neededKeys)); |
| 79 | + } |
| 80 | +} |
0 commit comments