1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Sco\Admin\Form\Elements; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
6
|
|
|
use Sco\Admin\Form\Elements\Concerns\HasOptions; |
7
|
|
|
|
8
|
|
|
class Tree extends NamedElement |
9
|
|
|
{ |
10
|
|
|
use HasOptions; |
11
|
|
|
|
12
|
|
|
protected $type = 'tree'; |
13
|
|
|
|
14
|
|
|
protected $defaultValue = []; |
15
|
|
|
|
16
|
|
|
public function __construct($name, $title, $options) |
17
|
|
|
{ |
18
|
|
|
parent::__construct($name, $title); |
19
|
|
|
|
20
|
|
|
$this->setOptions($options); |
21
|
|
|
} |
22
|
|
|
|
23
|
|
View Code Duplication |
public function getValue() |
|
|
|
|
24
|
|
|
{ |
25
|
|
|
$value = $this->getValueFromModel(); |
26
|
|
|
if (empty($value)) { |
27
|
|
|
return $value; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
if ($this->isOptionsModel() && $this->isRelation()) { |
31
|
|
|
$model = $this->getOptionsModel(); |
32
|
|
|
$key = $this->getOptionsValueAttribute() ?: $model->getKeyName(); |
33
|
|
|
|
34
|
|
|
$value = $value->pluck($key)->map(function ($item) { |
35
|
|
|
return (string)$item; |
36
|
|
|
}); |
37
|
|
|
} |
38
|
|
|
return $value; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function save() |
42
|
|
|
{ |
43
|
|
|
if (!($this->isOptionsModel() && $this->isRelation())) { |
44
|
|
|
parent::save(); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
|
View Code Duplication |
public function finishSave() |
|
|
|
|
49
|
|
|
{ |
50
|
|
|
if (!($this->isOptionsModel() && $this->isRelation())) { |
51
|
|
|
return; |
52
|
|
|
} |
53
|
|
|
$attribute = $this->getName(); |
54
|
|
|
$values = $this->getValueFromRequest(); |
55
|
|
|
|
56
|
|
|
$relation = $this->getModel()->{$attribute}(); |
57
|
|
|
if ($relation instanceof BelongsToMany) { |
58
|
|
|
$relation->sync($values); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
View Code Duplication |
protected function parseOptions($options) |
|
|
|
|
63
|
|
|
{ |
64
|
|
|
return collect($options)->mapWithKeys(function ($value, $key) { |
65
|
|
|
return [ |
66
|
|
|
$key => [ |
67
|
|
|
'id' => (string)$key, |
68
|
|
|
'label' => $value, |
69
|
|
|
], |
70
|
|
|
]; |
71
|
|
|
})->values(); |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
public function toArray() |
75
|
|
|
{ |
76
|
|
|
return parent::toArray() + [ |
77
|
|
|
'options' => $this->getOptions(), |
78
|
|
|
]; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
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.