summaryrefslogtreecommitdiff
path: root/src/Columns/Column.php
blob: 7b9f248fc9635b747c419aabb78b2b4aaa0472b0 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php

namespace Lightscale\LaralightTables\Columns;

use Illuminate\Database\Eloquent\Model;
use Illuminate\View\ComponentAttributeBag;

use Closure;

class Column {

    private TableComponent $table;

    private Closure $displayFn;
    private ?Closure $sortFn = null;
    private ?Closure $searchFn = null;
    private ?Closure $attributesFn = null;

    public function __construct(
        public string $name,
        public string $title
    ) {
        $this->displayFn = Closure::fromCallable([$this, 'defaultDisplay']);
    }

    public static function make(string $name, $title) : static
    {
        return new static($name, $title);
    }

    private function defaultDisplay(Model $row, Column $column)
    {
        return $row->{$column->name};
    }

    public function display(callable $fn) : static
    {
        $this->displayFn = Closure::fromCallable($fn);
        return $this;
    }

    public function sortable(callable $fn) : static
    {
        $this->sortFn = Closure::fromCallable($fn);
        return $this;
    }

    public function searchable(callable $fn) : static
    {
        $this->searchFn = Closure::fromCallable($fn);
        return $this;
    }

    public function attributes(callable $fn) : static
    {
        $this->attributesFn = Closure::fromCallable($fn);
        return $this;
    }

    public function view(Model $row)
    {
        $attributes = $this->attributesFn?->call($this, $row) ?? [];
        $attributes = new ComponentAttributeBag($attributes);
        $content = $this->displayFn->call($this, $row, $this);
        return view('laralight-tables::column', compact('attributes', 'content'));
    }

}