Completed
Push — master ( 3e3189...2724fd )
by Song
05:30 queued 03:12
created

SwitchDisplay::display()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 59

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 59
rs 8.8945
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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().$keys->reduce(function ($carry, $val) {
34
                return $carry."[$val]";
35
            });
36
        }
37
38
        $script = <<<EOT
39
40
$('.$class').bootstrapSwitch({
41
    size:'mini',
42
    onText: '{$this->states['on']['text']}',
43
    offText: '{$this->states['off']['text']}',
44
    onColor: '{$this->states['on']['color']}',
45
    offColor: '{$this->states['off']['color']}',
46
    onSwitchChange: function(event, state){
47
48
        $(this).val(state ? 'on' : 'off');
49
50
        var pk = $(this).data('key');
51
        var value = $(this).val();
52
53
        $.ajax({
54
            url: "{$this->grid->resource()}/" + pk,
55
            type: "POST",
56
            data: {
57
                "$key": value,
58
                _token: LA.token,
59
                _method: 'PUT'
60
            },
61
            success: function (data) {
62
                toastr.success(data.message);
63
            }
64
        });
65
    }
66
});
67
68
EOT;
69
70
        Admin::script($script);
71
72
        $key = $this->row->{$this->grid->getKeyName()};
73
74
        $checked = $this->states['on']['value'] == $this->value ? 'checked' : '';
75
76
        return <<<EOT
77
        <input type="checkbox" class="$class" $checked data-key="$key" />
78
EOT;
79
    }
80
}
81