Filterable::isFilterable()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace N7olkachev\LaravelFilterable;
4
5
use N7olkachev\LaravelFilterable\Exceptions\FilterableException;
6
7
trait Filterable
8
{
9
    public function scopeFilter($query, array $filterData = [])
10
    {
11
        foreach ($filterData as $key => $value) {
12
            if (!$this->isFilterable($key)) {
13
                throw new FilterableException("[$key] is not allowed for filtering");
14
            }
15
16
            if (is_null($value) || $value === '') continue;
17
18
            $scopeName = ucfirst(camel_case($key));
19
20
            if (method_exists($this, 'scope' . $scopeName)) {
21
                $query->$scopeName($value);
22
            } else if (is_array($value)) {
23
                $query->whereIn($key, $value);
24
            } else {
25
                $query->where($key, $value);
26
            }
27
        }
28
    }
29
30
    protected function isFilterable($key)
31
    {
32
        $filterable = $this->filterable ?: [];
0 ignored issues
show
Bug introduced by
The property filterable 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...
33
34
        return in_array($key, $filterable);
35
    }
36
}