Passed
Pull Request — master (#159)
by Alexander
04:51 queued 02:29
created

Label::forId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Form\Field\Part;
6
7
use Stringable;
8
use Yiisoft\Form\Field\Base\FormAttributeTrait;
9
use Yiisoft\Html\Tag\Label as LabelTag;
10
use Yiisoft\Widget\Widget;
11
12
final class Label extends Widget
13
{
14
    use FormAttributeTrait;
15
16
    private bool $setForAttribute = true;
17
18
    private ?string $forId = null;
19
    private bool $useInputIdAttribute = true;
20
21
    /**
22
     * @var string|Stringable|null
23
     */
24
    private $content = null;
25
26
    private bool $encode = true;
27
28 4
    public function setForAttribute(bool $value): self
29
    {
30 4
        $new = clone $this;
31 4
        $new->setForAttribute = $value;
32 4
        return $new;
33
    }
34
35
    /**
36
     * @return static
37
     */
38 5
    public function forId(?string $id): self
39
    {
40 5
        $new = clone $this;
41 5
        $new->forId = $id;
42 5
        return $new;
43
    }
44
45
    /**
46
     * @return static
47
     */
48 5
    public function useInputIdAttribute(bool $value): self
49
    {
50 5
        $new = clone $this;
51 5
        $new->useInputIdAttribute = $value;
52 5
        return $new;
53
    }
54
55
    /**
56
     * @param string|Stringable|null $content
57
     *
58
     * @return static
59
     */
60 7
    public function content($content): self
61
    {
62 7
        $new = clone $this;
63 7
        $new->content = $content;
64 7
        return $new;
65
    }
66
67
    /**
68
     * Whether content should be HTML-encoded.
69
     *
70
     * @param bool $value
71
     *
72
     * @return static
73
     */
74 1
    public function encode(bool $value): self
75
    {
76 1
        $new = clone $this;
77 1
        $new->encode = $value;
78 1
        return $new;
79
    }
80
81 43
    protected function run(): string
82
    {
83 43
        $tag = LabelTag::tag()->content(
84 43
            $this->content ?? $this->getAttributeLabel()
85
        );
86
87 43
        if ($this->setForAttribute) {
88 39
            $id = $this->forId;
89 39
            if ($id === null && $this->useInputIdAttribute) {
90 30
                $id = $this->getInputId();
91
            }
92 39
            if ($id !== null) {
93 35
                $tag = $tag->forId($id);
94
            }
95
        }
96
97 43
        if (!$this->encode) {
98 1
            $tag = $tag->encode(false);
99
        }
100
101 43
        return $tag->render();
102
    }
103
}
104