1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Encore\Admin\Form\Field; |
4
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany; |
6
|
|
|
|
7
|
|
|
class MultipleSelect extends Select |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* Other key for many-to-many relation. |
11
|
|
|
* |
12
|
|
|
* @var string |
13
|
|
|
*/ |
14
|
|
|
protected $otherKey; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* Get other key for this many-to-many relation. |
18
|
|
|
* |
19
|
|
|
* @throws \Exception |
20
|
|
|
* |
21
|
|
|
* @return string |
22
|
|
|
*/ |
23
|
|
|
protected function getOtherKey() |
24
|
|
|
{ |
25
|
|
|
if ($this->otherKey) { |
26
|
|
|
return $this->otherKey; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
if (is_callable([$this->form->model(), $this->column]) && |
30
|
|
|
($relation = $this->form->model()->{$this->column}()) instanceof BelongsToMany |
31
|
|
|
) { |
32
|
|
|
/* @var BelongsToMany $relation */ |
33
|
|
|
$fullKey = $relation->getQualifiedRelatedPivotKeyName(); |
34
|
|
|
$fullKeyArray = explode('.', $fullKey); |
35
|
|
|
|
36
|
|
|
return $this->otherKey = end($fullKeyArray); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
throw new \Exception('Column of this field must be a `BelongsToMany` relation.'); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
View Code Duplication |
public function fill($data) |
|
|
|
|
43
|
|
|
{ |
44
|
|
|
$relations = array_get($data, $this->column); |
|
|
|
|
45
|
|
|
|
46
|
|
|
if (is_string($relations)) { |
47
|
|
|
$this->value = explode(',', $relations); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if (is_array($relations)) { |
51
|
|
|
if (is_string(current($relations))) { |
52
|
|
|
$this->value = $relations; |
53
|
|
|
} else { |
54
|
|
|
foreach ($relations as $relation) { |
55
|
|
|
$this->value[] = array_get($relation, "pivot.{$this->getOtherKey()}"); |
56
|
|
|
} |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
} |
60
|
|
|
|
61
|
|
View Code Duplication |
public function setOriginal($data) |
|
|
|
|
62
|
|
|
{ |
63
|
|
|
$relations = array_get($data, $this->column); |
|
|
|
|
64
|
|
|
|
65
|
|
|
if (is_string($relations)) { |
66
|
|
|
$this->original = explode(',', $relations); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
if (is_array($relations)) { |
70
|
|
|
if (is_string(current($relations))) { |
71
|
|
|
$this->original = $relations; |
72
|
|
|
} else { |
73
|
|
|
foreach ($relations as $relation) { |
74
|
|
|
$this->original[] = array_get($relation, "pivot.{$this->getOtherKey()}"); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
public function prepare($value) |
81
|
|
|
{ |
82
|
|
|
$value = (array) $value; |
83
|
|
|
|
84
|
|
|
return array_filter($value); |
85
|
|
|
} |
86
|
|
|
} |
87
|
|
|
|
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.