Completed
Push — master ( 79d73c...7af0e6 )
by Song
05:52 queued 02:08
created

SwitchField::setSize()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Form\Field;
4
5
use Encore\Admin\Form\Field;
6
use Illuminate\Support\Arr;
7
8
class SwitchField extends Field
9
{
10
    protected static $css = [
11
        '/vendor/laravel-admin/bootstrap-switch/dist/css/bootstrap3/bootstrap-switch.min.css',
12
    ];
13
14
    protected static $js = [
15
        '/vendor/laravel-admin/bootstrap-switch/dist/js/bootstrap-switch.min.js',
16
    ];
17
18
    protected $states = [
19
        'on'  => ['value' => 1, 'text' => 'ON', 'color' => 'primary'],
20
        'off' => ['value' => 0, 'text' => 'OFF', 'color' => 'default'],
21
    ];
22
23
    protected $size = 'small';
24
25
    public function setSize($size)
26
    {
27
        $this->size = $size;
28
29
        return $this;
30
    }
31
32
    public function states($states = [])
33
    {
34
        foreach (Arr::dot($states) as $key => $state) {
35
            Arr::set($this->states, $key, $state);
36
        }
37
38
        return $this;
39
    }
40
41
    public function prepare($value)
42
    {
43
        if (isset($this->states[$value])) {
44
            return $this->states[$value]['value'];
45
        }
46
47
        return $value;
48
    }
49
50
    public function render()
51
    {
52
        foreach ($this->states as $state => $option) {
53
            if ($this->value() == $option['value']) {
54
                $this->value = $state;
55
                break;
56
            }
57
        }
58
59
        $this->script = <<<EOT
60
61
$('{$this->getElementClassSelector()}.la_checkbox').bootstrapSwitch({
62
    size:'{$this->size}',
63
    onText: '{$this->states['on']['text']}',
64
    offText: '{$this->states['off']['text']}',
65
    onColor: '{$this->states['on']['color']}',
66
    offColor: '{$this->states['off']['color']}',
67
    onSwitchChange: function(event, state) {
68
        $(event.target).closest('.bootstrap-switch').next().val(state ? 'on' : 'off').change();
69
    }
70
});
71
72
EOT;
73
74
        return parent::render();
0 ignored issues
show
Bug Compatibility introduced by
The expression parent::render(); of type string|Illuminate\View\V...\Contracts\View\Factory adds the type Illuminate\Contracts\View\Factory to the return on line 74 which is incompatible with the return type declared by the interface Illuminate\Contracts\Support\Renderable::render of type string.
Loading history...
75
    }
76
}
77