summaryrefslogtreecommitdiff
path: root/src/Toolbar/Filter.php
blob: 51e0d9a58ee706f08fbed863aa64f9619b2f3be9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php

namespace Lightscale\LaralightTables\Toolbar;

use Illuminate\Database\Eloquent\Builder;

use Closure;

abstract class Filter extends Item
{
    protected ?Closure $filterCallback = null;

    public function __construct(
        protected string $key,
        protected ?string $label = null,
    ) {}

    public function label(string $v): static
    {
        $this->label = $v;
        return $this;
    }

    public function makeId(): string
    {
        return "filter_{$this->key}";
    }

    public function filter(callable $filterCB): static
    {
        $this->filterCallback = $filterCB;
        return $this;
    }

    public function applyFilter(Builder $query): void
    {
        if ($this->filterCallback !== null) {
            $value = $this->getTable()->filters[$this->key] ?? null;

            if (!empty($value)) {
                ($this->filterCallback)($query, $value);
            }
        }
    }

}