Passed
Pull Request — master (#192)
by Alexander
04:44 queued 02:17
created

Label::content()   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\Html;
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 5
    public function forId(?string $id): self
36
    {
37 5
        $new = clone $this;
38 5
        $new->forId = $id;
39 5
        return $new;
40
    }
41
42
    /**
43
     * @return static
44
     */
45 20
    public function useInputIdAttribute(bool $value): self
46
    {
47 20
        $new = clone $this;
48 20
        $new->useInputIdAttribute = $value;
49 20
        return $new;
50
    }
51
52
    /**
53
     * @return static
54
     */
55 8
    public function content(string|Stringable|null $content): self
56
    {
57 8
        $new = clone $this;
58 8
        $new->content = $content;
59 8
        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 141
    protected function run(): string
75
    {
76 141
        $useModel = $this->hasFormModelAndAttribute();
77
78 141
        $content = $useModel
79 109
            ? $this->content ?? $this->getAttributeLabel()
80 34
            : (string) $this->content;
81
82 141
        if ($content === '') {
83 34
            return '';
84
        }
85
86 109
        $tag = Html::label($content);
87
88 109
        if ($this->setForAttribute) {
89 105
            $id = $this->forId;
90 105
            if ($useModel && $id === null && $this->useInputIdAttribute) {
91 80
                $id = $this->getInputId();
92
            }
93 105
            if ($id !== null) {
94 85
                $tag = $tag->forId($id);
95
            }
96
        }
97
98 109
        if (!$this->encode) {
99 1
            $tag = $tag->encode(false);
100
        }
101
102 109
        return $tag->render();
103
    }
104
}
105