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

Hint::run()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

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