DynamicBooleanFilter::apply()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 7
c 1
b 0
f 0
dl 0
loc 12
ccs 9
cts 9
cp 1
rs 10
cc 3
nc 3
nop 3
crap 3
1
<?php
2
3
namespace NovaThinKit\Nova\Filters;
4
5
use Illuminate\Database\Eloquent\Builder;
6
use Illuminate\Support\Str;
7
use Laravel\Nova\Filters\BooleanFilter;
8
use Laravel\Nova\Http\Requests\NovaRequest;
9
use Laravel\Nova\Nova;
10
11
class DynamicBooleanFilter extends BooleanFilter
12
{
13
    protected string $fieldName;
14
15
    protected array $optionsData;
16
17
    /**
18
     * Filter not current entity but relation.
19
     *
20
     * @var string|null
21
     */
22
    protected ?string $forRelation = null;
23
24 3
    public function __construct(
25
        array   $optionsData,
26
        string  $fieldName = 'type',
27
        ?string $name = null,
28
    ) {
29 3
        $this->optionsData = $optionsData;
30 3
        $this->fieldName   = $fieldName;
31 3
        $this->name        = $name ?: Nova::humanize($fieldName);
32
    }
33
34 2
    public function apply(NovaRequest $request, $query, $value)
35
    {
36 2
        $values = array_keys(array_filter($value));
37 2
        if (count($values) > 0) {
38 2
            if ($this->forRelation) {
39 1
                return $query->whereHas(
40 1
                    $this->forRelation,
41 1
                    fn (Builder $q) => $q->whereIn($this->fieldName, $values)
42 1
                );
43
            }
44
45 1
            return $query->whereIn($this->fieldName, $values);
46
        }
47
    }
48
49 1
    public function options(NovaRequest $request): array
50
    {
51 1
        return $this->optionsData;
52
    }
53
54 1
    public function key(): string
55
    {
56 1
        $key = parent::key();
57
58 1
        return Str::kebab("{$key}-{$this->fieldName}-{$this->name()}");
59
    }
60
61 1
    public function forRelation(?string $forRelation = null): static
62
    {
63 1
        $this->forRelation = $forRelation;
64
65 1
        return $this;
66
    }
67
}
68