Completed
Push — master ( 797ef7...545216 )
by wen
13:55
created

MultiSelect::save()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 6
c 1
b 0
f 0
rs 9.4285
cc 3
eloc 3
nc 2
nop 0
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
    public function getValue()
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 View Code Duplication
    public function finishSave()
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...
32
    {
33
        if (!($this->isOptionsModel() && $this->isRelation())) {
34
            return;
35
        }
36
        $attribute = $this->getName();
37
        $values = $this->getValueFromRequest();
38
39
        $relation = $this->getModel()->{$attribute}();
40
        if ($relation instanceof BelongsToMany) {
41
            $relation->sync($values);
42
        }
43
    }
44
45
    public function toArray()
46
    {
47
        return parent::toArray() + [
48
                'multiple' => true,
49
            ];
50
    }
51
}
52