Passed
Pull Request — master (#192)
by Alexander
28:18 queued 25:44
created

Hint   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 67
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
c 1
b 0
f 0
dl 0
loc 67
ccs 27
cts 27
cp 1
rs 10
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A content() 0 5 1
A tag() 0 9 2
A run() 0 11 3
A tagAttributes() 0 5 1
A encode() 0 5 1
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
/**
14
 * Represents hint for a form field.
15
 */
16
final class Hint extends Widget
17
{
18
    use FormAttributeTrait;
19
20
    /**
21
     * @psalm-var non-empty-string
22
     */
23
    private string $tag = 'div';
24
    private array $tagAttributes = [];
25
26
    private string|Stringable|null $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.
34
     */
35 5
    public function tag(string $tag): self
36
    {
37 5
        if ($tag === '') {
38 1
            throw new InvalidArgumentException('Tag name cannot be empty.');
39
        }
40
41 4
        $new = clone $this;
42 4
        $new->tag = $tag;
43 4
        return $new;
44
    }
45
46 4
    public function tagAttributes(array $attributes): self
47
    {
48 4
        $new = clone $this;
49 4
        $new->tagAttributes = $attributes;
50 4
        return $new;
51
    }
52
53 7
    public function content(string|Stringable|null $content): self
54
    {
55 7
        $new = clone $this;
56 7
        $new->content = $content;
57 7
        return $new;
58
    }
59
60
    /**
61
     * Whether content should be HTML-encoded.
62
     *
63
     * @param bool $value
64
     */
65 2
    public function encode(bool $value): self
66
    {
67 2
        $new = clone $this;
68 2
        $new->encode = $value;
69 2
        return $new;
70
    }
71
72 422
    protected function run(): string
73
    {
74 422
        $content = $this->hasFormModelAndAttribute()
75 342
            ? $this->content ?? $this->getAttributeHint()
76 82
            : (string) $this->content;
77
78 422
        return $content === ''
79 367
            ? ''
80 55
            : Html::tag($this->tag, $content, $this->tagAttributes)
81 55
                ->encode($this->encode)
82 422
                ->render();
83
    }
84
}
85