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

FormAttributeTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
dl 0
loc 56
ccs 24
cts 24
cp 1
rs 10
c 1
b 0
f 0
wmc 11

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getFirstError() 0 3 1
A getAttributeValue() 0 3 1
A getAttributeHint() 0 3 1
A getInputId() 0 3 1
A getFormModel() 0 7 2
A attribute() 0 6 1
A getAttributeName() 0 3 1
A getAttributePlaceholder() 0 4 2
A getAttributeLabel() 0 3 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Form\Field\Base;
6
7
use InvalidArgumentException;
8
use Yiisoft\Form\FormModelInterface;
9
use Yiisoft\Form\Helper\HtmlForm;
10
11
trait FormAttributeTrait
12
{
13
    private ?FormModelInterface $formModel = null;
14
    private string $attribute = '';
15
16 108
    final public function attribute(FormModelInterface $formModel, string $attribute): static
17
    {
18 108
        $new = clone $this;
19 108
        $new->formModel = $formModel;
20 108
        $new->attribute = $attribute;
21 108
        return $new;
22
    }
23
24 101
    final protected function getFormModel(): FormModelInterface
25
    {
26 101
        if ($this->formModel === null) {
27 1
            throw new InvalidArgumentException('Form model is not set.');
28
        }
29
30 100
        return $this->formModel;
31
    }
32
33 79
    final protected function getAttributeName(): string
34
    {
35 79
        return HtmlForm::getAttributeName($this->getFormModel(), $this->attribute);
36
    }
37
38 66
    final protected function getAttributeValue(): mixed
39
    {
40 66
        return HtmlForm::getAttributeValue($this->getFormModel(), $this->attribute);
41
    }
42
43 69
    final protected function getAttributeLabel(): string
44
    {
45 69
        return HtmlForm::getAttributeLabel($this->getFormModel(), $this->attribute);
46
    }
47
48 72
    final protected function getAttributeHint(): string
49
    {
50 72
        return HtmlForm::getAttributeHint($this->getFormModel(), $this->attribute);
51
    }
52
53 35
    final protected function getAttributePlaceholder(): ?string
54
    {
55 35
        $placeholder = $this->getFormModel()->getAttributePlaceholder($this->getAttributeName());
56 35
        return $placeholder === '' ? null : $placeholder;
57
    }
58
59 68
    final protected function getInputId(): string
60
    {
61 68
        return HtmlForm::getInputId($this->getFormModel(), $this->attribute);
62
    }
63
64 79
    final protected function getFirstError(): ?string
65
    {
66 79
        return $this->getFormModel()->getFormErrors()->getFirstError($this->getAttributeName());
67
    }
68
}
69