Completed
Pull Request — master (#14)
by Sebastian
03:03
created

Select::hasSelection()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace Spatie\Html\Elements;
4
5
use Spatie\Html\Selectable;
6
use Spatie\Html\BaseElement;
7
8
class Select extends BaseElement
9
{
10
    /** @var string */
11
    protected $tag = 'select';
12
13
    /** @var array */
14
    protected $options = [];
15
16
    /** @var string */
17
    protected $value = '';
18
19
    /**
20
     * @param string $name
21
     *
22
     * @return static
23
     */
24
    public function name(?string $name)
25
    {
26
        return $this->attribute('name', $name);
27
    }
28
29
    /**
30
     * @param iterable $options
31
     *
32
     * @return static
33
     */
34
    public function options(iterable $options)
35
    {
36
        return $this->addChildren($options, function ($text, $value) {
37
            return Option::create()
38
                ->value($value)
39
                ->text($text)
40
                ->selectedIf($value === $this->value);
41
        });
42
    }
43
44
    public function placeholder(string $text)
45
    {
46
        return $this->prependChild(
47
            Option::create()
48
                ->text($text)
49
                ->selectedIf(! $this->hasSelection())
50
        );
51
    }
52
53
    /**
54
     * @param string $value
55
     *
56
     * @return static
57
     */
58
    public function value(?string $value)
59
    {
60
        $element = clone $this;
61
62
        $element->value = $value;
63
64
        $element->applyValueToOptions();
65
66
        return $element;
67
    }
68
69
    protected function hasSelection(): bool
70
    {
71
        return $this->children->contains->hasAttribute('selected');
72
    }
73
74
    protected function applyValueToOptions()
75
    {
76
        $this->children = $this->children->map(function ($child) {
77
            if ($child instanceof Selectable) {
78
                return $child->selectedIf($this->value === $child->getAttribute('value'));
79
            }
80
81
            return $child;
82
        });
83
    }
84
}
85