Completed
Push — master ( 062b68...81f5ad )
by Terzi
08:48
created

BelongsToMany::withTitleField()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Terranet\Administrator\Field;
4
5
use Terranet\Administrator\Modules\Faked;
6
7
class BelongsToMany extends HasMany
8
{
9
    const MODE_TAGS = 'tags';
10
    const MODE_CHECKBOXES = 'checkboxes';
11
12
    /** @var string */
13
    protected $icon = 'random';
14
15
    /** @var string */
16
    protected $titleField = 'name';
17
18
    /** @var string */
19
    protected $editMode = self::MODE_CHECKBOXES;
20
21
    /** @var bool */
22
    protected $completeList = true;
23
24
    /**
25
     * Show editable controls as checkboxes.
26
     *
27
     * @return self
28
     */
29
    public function tagList(): self
30
    {
31
        $this->editMode = static::MODE_TAGS;
32
        $this->completeList = false;
33
34
        return $this;
35
    }
36
37
    /**
38
     * @param string $column
39
     * @return BelongsToMany
40
     */
41
    public function withTitleField(string $column): BelongsToMany
42
    {
43
        $this->titleField = $column;
44
45
        return $this;
46
    }
47
48
    /**
49
     * @return array
50
     */
51
    public function onEdit(): array
52
    {
53
        $relation = $this->model->{$this->id()}();
54
        if (static::MODE_CHECKBOXES === $this->editMode && $this->completeList) {
55
            $values = $relation->getRelated()->all();
56
        } else {
57
            $values = $this->value();
58
        }
59
60
        if ($module = $this->firstWithModel($relation->getRelated())) {
61
            $titleField = $module::$title;
62
        } else {
63
            $module = Faked::make($relation->getRelated());
0 ignored issues
show
Unused Code introduced by
The assignment to $module is dead and can be removed.
Loading history...
64
            $titleField = $this->titleField;
65
        }
66
67
        return [
68
            'relation' => $relation,
69
            'values' => $values,
70
            'completeList' => $this->completeList,
71
            'titleField' => $titleField,
72
            'editMode' => $this->editMode,
73
        ];
74
    }
75
}
76