Passed
Pull Request — master (#192)
by Alexander
02:31
created

Label::run()   A

Complexity

Conditions 6
Paths 10

Size

Total Lines 21
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 11
nc 10
nop 0
dl 0
loc 21
ccs 12
cts 12
cp 1
crap 6
rs 9.2222
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
    private string|Stringable|null $content = null;
22
23
    private bool $encode = true;
24
25 4
    public function setForAttribute(bool $value): self
26
    {
27 4
        $new = clone $this;
28 4
        $new->setForAttribute = $value;
29 4
        return $new;
30
    }
31
32
    /**
33
     * @return static
34
     */
35 4
    public function forId(?string $id): self
36
    {
37 4
        $new = clone $this;
38 4
        $new->forId = $id;
39 4
        return $new;
40
    }
41
42
    /**
43
     * @return static
44
     */
45 5
    public function useInputIdAttribute(bool $value): self
46
    {
47 5
        $new = clone $this;
48 5
        $new->useInputIdAttribute = $value;
49 5
        return $new;
50
    }
51
52
    /**
53
     * @return static
54
     */
55 7
    public function content(string|Stringable|null $content): self
56
    {
57 7
        $new = clone $this;
58 7
        $new->content = $content;
59 7
        return $new;
60
    }
61
62
    /**
63
     * Whether content should be HTML-encoded.
64
     *
65
     * @return static
66
     */
67 1
    public function encode(bool $value): self
68
    {
69 1
        $new = clone $this;
70 1
        $new->encode = $value;
71 1
        return $new;
72
    }
73
74 57
    protected function run(): string
75
    {
76 57
        $tag = LabelTag::tag()->content(
77 57
            $this->content ?? $this->getAttributeLabel()
78
        );
79
80 57
        if ($this->setForAttribute) {
81 53
            $id = $this->forId;
82 53
            if ($id === null && $this->useInputIdAttribute) {
83 45
                $id = $this->getInputId();
84
            }
85 53
            if ($id !== null) {
86 49
                $tag = $tag->forId($id);
87
            }
88
        }
89
90 57
        if (!$this->encode) {
91 1
            $tag = $tag->encode(false);
92
        }
93
94 57
        return $tag->render();
95
    }
96
}
97