Completed
Push — master ( 9e9952...fdd34c )
by Terzi
04:01
created

HasOne::onIndex()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 12
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Terranet\Administrator\Field;
4
5
use Terranet\Administrator\Collection\Mutable;
6
use Terranet\Administrator\Traits\Module\HasColumns;
7
8
class HasOne extends BelongsTo
9
{
10
    use HasColumns;
0 ignored issues
show
Bug introduced by
The trait Terranet\Administrator\Traits\Module\HasColumns requires the property $includeDateColumns which is not provided by Terranet\Administrator\Field\HasOne.
Loading history...
11
12
    /** @var null|array */
13
    protected $only;
14
15
    /** @var null|array */
16
    protected $except;
17
18
    /**
19
     * @param array $only
20
     *
21
     * @return self
22
     */
23
    public function only(array $only): self
24
    {
25
        $this->only = $only;
26
27
        return $this;
28
    }
29
30
    /**
31
     * @param array $except
32
     *
33
     * @return self
34
     */
35
    public function except(array $except): self
36
    {
37
        $this->except = $except;
38
39
        return $this;
40
    }
41
42
    /**
43
     * @return array
44
     */
45
    protected function onEdit(): array
46
    {
47
        $relation = $this->model->{$this->id()}();
48
49
        $columns = $this->relatedColumns($relation->getRelated())
50
                        ->each(function ($field) {
51
                            $field->setId(
52
                                "{$this->id()}.{$field->id()}"
53
                            );
54
                        });
55
56
        return [
57
            'columns' => $columns,
58
        ];
59
    }
60
61
    /**
62
     * @return array
63
     */
64
    protected function onIndex(): array
65
    {
66
        $relation = $this->model->{$this->id()}();
67
68
        $columns = $this->relatedColumns($relation->getRelated())
69
                        ->filter(function ($field) {
70
                            return !$field instanceof Textarea;
71
                        });
72
73
        return [
74
            'columns' => $columns,
75
            'related' => $this->model->{$this->id()},
76
        ];
77
    }
78
79
    /**
80
     * @param $related
81
     * @return \Terranet\Administrator\Collection\Mutable
82
     */
83
    protected function relatedColumns($related): Mutable
84
    {
85
        return $this->collectColumns($related)
86
                    ->except(array_merge([$related->getKeyName()], $this->except ?? []))
87
                    ->only($this->only);
88
    }
89
}
90