Completed
Push — master ( 62a574...40c09d )
by
unknown
01:52
created

FiltersQuery::findFilter()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Spatie\QueryBuilder\Concerns;
4
5
use Illuminate\Support\Collection;
6
use Spatie\QueryBuilder\Exceptions\InvalidFilterQuery;
7
use Spatie\QueryBuilder\Filter;
8
9
trait FiltersQuery
10
{
11
    /** @var \Illuminate\Support\Collection */
12
    protected $allowedFilters;
13
14
    public function allowedFilters($filters): self
15
    {
16
        $filters = is_array($filters) ? $filters : func_get_args();
17
        $this->allowedFilters = collect($filters)->map(function ($filter) {
18
            if ($filter instanceof Filter) {
19
                return $filter;
20
            }
21
22
            return Filter::partial($filter);
23
        });
24
25
        $this->guardAgainstUnknownFilters();
26
27
        $this->addFiltersToQuery($this->request->filters());
0 ignored issues
show
Bug introduced by
The property request does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
28
29
        return $this;
30
    }
31
32
    protected function addFiltersToQuery(Collection $filters)
33
    {
34
        $filters->each(function ($value, $property) {
35
            $filter = $this->findFilter($property);
36
37
            $filter->filter($this, $value);
38
        });
39
    }
40
41
    protected function findFilter(string $property): ?Filter
42
    {
43
        return $this->allowedFilters
44
            ->first(function (Filter $filter) use ($property) {
45
                return $filter->isForProperty($property);
46
            });
47
    }
48
49
    protected function guardAgainstUnknownFilters()
50
    {
51
        $filterNames = $this->request->filters()->keys();
52
53
        $allowedFilterNames = $this->allowedFilters->map->getProperty();
54
55
        $diff = $filterNames->diff($allowedFilterNames);
56
57
        if ($diff->count()) {
58
            throw InvalidFilterQuery::filtersNotAllowed($diff, $allowedFilterNames);
59
        }
60
    }
61
}
62