Completed
Push — master ( fe60d0...675c3f )
by wen
11:50
created

MultiSelect::prepareValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
1
<?php
2
3
namespace Sco\Admin\Form\Elements;
4
5
use Illuminate\Database\Eloquent\Model;
6
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
7
use Illuminate\Http\Request;
8
9
class MultiSelect extends Select
10
{
11
    protected $defaultValue = [];
12
13 View Code Duplication
    public function getValue()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
14
    {
15
        $value = $this->getValueFromModel();
16
        if (empty($value)) {
17
            return $value;
18
        }
19
20
        if ($this->isOptionsModel() && $this->isRelation()) {
21
            $model = $this->getOptionsModel();
22
            $key = $this->getOptionsValueAttribute() ?: $model->getKeyName();
23
24
            $value = $value->pluck($key)->map(function ($item) {
25
                return (string)$item;
26
            });
27
        }
28
        return $value;
29
    }
30
31
    protected function isOptionsModel()
32
    {
33
        return is_string($this->options) || $this->options instanceof Model;
34
    }
35
36
    protected function isRelation()
37
    {
38
        return method_exists($this->getModel(), $this->getName());
39
    }
40
41
    public function save()
42
    {
43
        if (!($this->isOptionsModel() && $this->isRelation())) {
44
            parent::save();
45
        }
46
    }
47
48
    protected function prepareValue($value)
49
    {
50
        if (!is_array($value)) {
51
            return $value;
52
        }
53
54
        return implode(',', $value);
55
    }
56
57
    public function finishSave()
58
    {
59
        if (!($this->isOptionsModel() && $this->isRelation())) {
60
            return;
61
        }
62
        $attribute = $this->getName();
63
        $values = $this->getValueFromRequest();
64
65
        $relation = $this->getModel()->{$attribute}();
66
        if ($relation instanceof BelongsToMany) {
67
            $relation->sync($values);
68
        }
69
    }
70
71
    public function toArray()
72
    {
73
        return parent::toArray() + [
74
                'multiple' => true,
75
            ];
76
    }
77
}
78