1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sfneal\Queries; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Builder; |
6
|
|
|
use Sfneal\Queries\Interfaces\DynamicQuery; |
7
|
|
|
use Sfneal\Queries\Traits\ApplyFilter; |
8
|
|
|
|
9
|
|
|
abstract class AbstractQueryWithFilters extends AbstractQuery implements DynamicQuery |
10
|
|
|
{ |
11
|
|
|
use ApplyFilter; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Array of attribute/form input name keys and Filter class values. |
15
|
|
|
* |
16
|
|
|
* @var array |
17
|
|
|
*/ |
18
|
|
|
public $attribute_filters; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Filter values to be passed to Filer classes. |
22
|
|
|
* |
23
|
|
|
* @var array |
24
|
|
|
*/ |
25
|
|
|
public $filters; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* QueryWithFilters constructor. |
29
|
|
|
* |
30
|
|
|
* @param array $filters |
31
|
|
|
*/ |
32
|
|
|
public function __construct(array $filters) |
33
|
|
|
{ |
34
|
|
|
// Remove invalid filters prior to executing query |
35
|
|
|
$this->filters = $this->filterFilters($filters); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Apply Filter decorators to the query if both the parameter is given and the Filter class exists. |
40
|
|
|
* |
41
|
|
|
* @param Builder $builder |
42
|
|
|
* @param array|null $filters |
43
|
|
|
* @return Builder |
44
|
|
|
*/ |
45
|
|
|
public function applyFiltersToQuery(Builder $builder, array $filters = null) |
46
|
|
|
{ |
47
|
|
|
// Wrap scopes |
48
|
|
|
$builder->where(function (Builder $query) use ($filters) { |
49
|
|
|
|
50
|
|
|
// Check every parameter to see if there's a corresponding Filter class |
51
|
|
|
foreach ($filters ?? $this->filters as $filterName => $value) { |
52
|
|
|
|
53
|
|
|
// Apply Filter class if it exists and is a filterable attribute |
54
|
|
|
$query = self::applyFilterToQuery($query, $filterName, $value); |
|
|
|
|
55
|
|
|
} |
56
|
|
|
}); |
57
|
|
|
|
58
|
|
|
return $builder; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* Parse filters and remove all keys that are not found in the declared attributes_filters. |
63
|
|
|
* |
64
|
|
|
* @param array $filters filters passed from search form |
65
|
|
|
* @return array |
66
|
|
|
*/ |
67
|
|
|
private function filterFilters(array $filters): array |
68
|
|
|
{ |
69
|
|
|
return array_filter($filters, function ($value, $filter) { |
70
|
|
|
|
71
|
|
|
// Return true if the filter is a filterable attribute |
72
|
|
|
return in_array($filter, array_keys($this->attribute_filters)) && ! is_null($value); |
73
|
|
|
}, ARRAY_FILTER_USE_BOTH); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|