DynamicFilter   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 80
rs 10
c 0
b 0
f 0
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setQuery() 0 3 1
A apply() 0 22 4
A arrayValueClause() 0 5 1
A stringValueClause() 0 5 1
1
<?php
2
3
namespace Sfneal\Filters;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Sfneal\Helpers\Strings\StringHelpers;
7
8
abstract class DynamicFilter implements Filter
9
{
10
    /**
11
     * @var Builder
12
     */
13
    protected $query;
14
15
    /**
16
     * @var string
17
     */
18
    protected $column = 'id';
19
20
    /**
21
     * Apply a given search value to the builder instance.
22
     *
23
     *  - if a 'string' value is found then a single value where clause is added
24
     *  - if a 'array' value is found then a whereIn clause is added
25
     *
26
     * @param  Builder  $query
27
     * @param  mixed  $value
28
     * @return Builder $query
29
     */
30
    public function apply(Builder $query, $value = null)
31
    {
32
        // Set the Query
33
        $this->setQuery($query);
34
35
        // Remove whitespace from the value
36
        if (is_string($value)) {
37
            $value = trim($value);
38
        }
39
40
        // Determine if the the ID's are a comma or space separated list
41
        // if true, add where clause looking for an array of ID's
42
        if (is_string($value) && $ids = (new StringHelpers($value))->isListString()) {
43
            $this->query = $this->arrayValueClause($ids);
44
        }
45
46
        // Add where clause searching for a single Plan ID
47
        else {
48
            $this->query = $this->stringValueClause($value);
49
        }
50
51
        return $this->query;
52
    }
53
54
    /**
55
     * Add a where clause that searches for a single value.
56
     *
57
     * @param  string  $id
58
     * @return Builder
59
     */
60
    protected function stringValueClause($id)
61
    {
62
        $this->query->whereIn($this->column, (array) $id);
63
64
        return $this->query;
65
    }
66
67
    /**
68
     * Add a where clause that searches for an array of values.
69
     *
70
     * @param  array  $ids
71
     * @return Builder
72
     */
73
    protected function arrayValueClause(array $ids)
74
    {
75
        $this->query->whereIn($this->column, $ids);
76
77
        return $this->query;
78
    }
79
80
    /**
81
     * Set the Query Builder property.
82
     *
83
     * @param  Builder  $query
84
     */
85
    private function setQuery(Builder $query): void
86
    {
87
        $this->query = $query;
88
    }
89
}
90