FilterableQuery::filterFilters()   A
last analyzed

Complexity

Conditions 2
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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