Completed
Push — master ( f71a30...1681a3 )
by Song
02:56
created

KeyValue::render()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Encore\Admin\Form\Field;
4
5
use Encore\Admin\Admin;
6
use Encore\Admin\Form\Field;
7
use Illuminate\Support\Arr;
8
9
class KeyValue extends Field
10
{
11
    /**
12
     * {@inheritdoc}
13
     */
14
    public function getValidator(array $input)
15
    {
16
        if ($this->validator) {
17
            return $this->validator->call($this, $input);
18
        }
19
20
        if (!is_string($this->column)) {
21
            return false;
22
        }
23
24
        $rules = $attributes = [];
25
26
        if (!$fieldRules = $this->getRules()) {
27
            return false;
28
        }
29
30
        if (!Arr::has($input, $this->column)) {
31
            return false;
32
        }
33
34
        $rules["{$this->column}.keys.*"] = 'distinct';
35
        $rules["{$this->column}.values.*"] = $fieldRules;
36
        $attributes["{$this->column}.keys.*"] = __('Key');
37
        $attributes["{$this->column}.values.*"] = __('Value');
38
39
        return validator($input, $rules, $this->getValidationMessages(), $attributes);
40
    }
41
42
    protected function setupScript()
43
    {
44
        $this->script = <<<SCRIPT
45
46
$('.{$this->column}-add').on('click', function () {
47
    var tpl = $('template.{$this->column}-tpl').html();
48
    $('tbody.kv-{$this->column}-table').append(tpl);
49
});
50
51
$('tbody').on('click', '.{$this->column}-remove', function () {
52
    $(this).closest('tr').remove();
53
});
54
55
SCRIPT;
56
    }
57
58
    public function prepare($value)
59
    {
60
        return array_combine($value['keys'], $value['values']);
61
    }
62
63
    public function render()
64
    {
65
        $this->setupScript();
66
67
        Admin::style('td .form-group {margin-bottom: 0 !important;}');
68
69
        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 69 which is incompatible with the return type declared by the interface Illuminate\Contracts\Support\Renderable::render of type string.
Loading history...
70
    }
71
}