Passed
Push — master ( bb0e2b...eaa23b )
by Stephen
01:06 queued 10s
created

AbstractFilterableQuery::filterFilters()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 1
nop 1
dl 0
loc 7
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sfneal\Queries;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Sfneal\Queries\Traits\HasFilters;
7
8
abstract class AbstractFilterableQuery implements Query
9
{
10
    use HasFilters;
11
12
    /**
13
     * Filter values to be passed to Filer classes.
14
     *
15
     * @var array
16
     */
17
    private $filters;
18
19
    /**
20
     * QueryWithFilters constructor.
21
     *
22
     * @param array|string $filters
23
     */
24
    public function __construct($filters)
25
    {
26
        // Array of Filters with dynamic values
27
        if (is_array($filters)) {
28
            // Remove invalid filters prior to executing query
29
            $this->filters = $this->filterFilters($filters);
30
        }
31
32
        // Single Filter without a dynamic value
33
        else {
34
            $this->filters = [$filters => null];
35
        }
36
    }
37
38
    /**
39
     * Execute a DB query using filter parameters.
40
     *
41
     * @return Builder
42
     */
43
    public function execute(): Builder
44
    {
45
        // Initialize query
46
        $query = $this->builder();
47
48
        // Apply filters
49
        $query = $this->filterQuery($query);
50
51
        // Return query
52
        return $query;
53
    }
54
55
    /**
56
     * Parse filters and remove all keys that are not found in the declared attributes_filters.
57
     *
58
     * @param array $filters filters passed from search form
59
     * @return array
60
     */
61
    private function filterFilters(array $filters): array
62
    {
63
        return array_filter($filters, function ($value, $filter) {
64
65
            // Return true if the filter is a filterable attribute
66
            return in_array($filter, array_keys($this->queryFilters())) && ! is_null($value);
67
        }, ARRAY_FILTER_USE_BOTH);
68
    }
69
}
70