Passed
Pull Request — master (#192)
by Sergei
03:23
created

Label::run()   B

Complexity

Conditions 9
Paths 22

Size

Total Lines 29
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 9

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 9
eloc 16
nc 22
nop 0
dl 0
loc 29
ccs 17
cts 17
cp 1
crap 9
rs 8.0555
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\Html;
10
use Yiisoft\Widget\Widget;
11
12
/**
13
 * Represents label for a form field.
14
 */
15
final class Label extends Widget
16
{
17
    use FormAttributeTrait;
18
19
    private bool $setForAttribute = true;
20
21
    private ?string $forId = null;
22
    private bool $useInputIdAttribute = true;
23
24
    private string|Stringable|null $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 20
    public function useInputIdAttribute(bool $value): self
49
    {
50 20
        $new = clone $this;
51 20
        $new->useInputIdAttribute = $value;
52 20
        return $new;
53
    }
54
55
    /**
56
     * @return static
57
     */
58 8
    public function content(string|Stringable|null $content): self
59
    {
60 8
        $new = clone $this;
61 8
        $new->content = $content;
62 8
        return $new;
63
    }
64
65
    /**
66
     * Whether content should be HTML-encoded.
67
     *
68
     * @return static
69
     */
70 1
    public function encode(bool $value): self
71
    {
72 1
        $new = clone $this;
73 1
        $new->encode = $value;
74 1
        return $new;
75
    }
76
77 185
    protected function run(): string
78
    {
79 185
        $useModel = $this->hasFormModelAndAttribute();
80
81 185
        $content = $useModel
82 124
            ? $this->content ?? $this->getAttributeLabel()
83 63
            : (string) $this->content;
84
85 185
        if ($content === '') {
86 63
            return '';
87
        }
88
89 124
        $tag = Html::label($content);
90
91 124
        if ($this->setForAttribute) {
92 120
            $id = $this->forId;
93 120
            if ($useModel && $id === null && $this->useInputIdAttribute) {
94 95
                $id = $this->getInputId();
95
            }
96 120
            if ($id !== null) {
97 100
                $tag = $tag->forId($id);
98
            }
99
        }
100
101 124
        if (!$this->encode) {
102 1
            $tag = $tag->encode(false);
103
        }
104
105 124
        return $tag->render();
106
    }
107
}
108