Completed
Pull Request — master (#2548)
by
unknown
02:28
created

SwitchDisplay   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
dl 0
loc 75
rs 10
c 0
b 0
f 0
wmc 5
lcom 1
cbo 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A updateStates() 0 6 2
B display() 0 60 3
1
<?php
2
3
namespace Encore\Admin\Grid\Displayers;
4
5
use Encore\Admin\Admin;
6
7
class SwitchDisplay extends AbstractDisplayer
8
{
9
    protected $states = [
10
        'on'  => ['value' => 1, 'text' => 'ON', 'color' => 'primary'],
11
        'off' => ['value' => 0, 'text' => 'OFF', 'color' => 'default'],
12
    ];
13
14
    protected function updateStates($states)
15
    {
16
        foreach (array_dot($states) as $key => $state) {
17
            array_set($this->states, $key, $state);
18
        }
19
    }
20
21
    public function display($states = [])
22
    {
23
        $this->updateStates($states);
24
25
        $name = $this->column->getName();
26
27
        $class = "grid-switch-" . str_replace('.', '-', $name);
28
29
        $keys = collect(explode('.', $name));
30
        if ($keys->isEmpty()) {
31
            $key = $name;
32
        } else {
33
            $key = $keys->shift()
34
                . $keys->reduce(function ($carry, $val) {
35
                    return $carry . "[$val]";}
36
                );
37
        }
38
39
        $script = <<<EOT
40
41
$('.$class').bootstrapSwitch({
42
    size:'mini',
43
    onText: '{$this->states['on']['text']}',
44
    offText: '{$this->states['off']['text']}',
45
    onColor: '{$this->states['on']['color']}',
46
    offColor: '{$this->states['off']['color']}',
47
    onSwitchChange: function(event, state){
48
49
        $(this).val(state ? 'on' : 'off');
50
51
        var pk = $(this).data('key');
52
        var value = $(this).val();
53
54
        $.ajax({
55
            url: "{$this->grid->resource()}/" + pk,
56
            type: "POST",
57
            data: {
58
                "$key": value,
59
                _token: LA.token,
60
                _method: 'PUT'
61
            },
62
            success: function (data) {
63
                toastr.success(data.message);
64
            }
65
        });
66
    }
67
});
68
69
EOT;
70
71
        Admin::script($script);
72
73
        $key = $this->row->{$this->grid->getKeyName()};
74
75
        $checked = $this->states['on']['value'] == $this->value ? 'checked' : '';
76
77
        return <<<EOT
78
        <input type="checkbox" class="$class" $checked data-key="$key" />
79
EOT;
80
    }
81
}
82