Passed
Pull Request — master (#159)
by Sergei
02:38
created

FormAttributeTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
dl 0
loc 62
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 Stringable;
9
use Yiisoft\Form\FormModelInterface;
10
use Yiisoft\Form\Helper\HtmlForm;
11
12
trait FormAttributeTrait
13
{
14
    private ?FormModelInterface $formModel = null;
15
    private string $attribute = '';
16
17
    /**
18
     * @return static
19
     */
20 74
    final public function attribute(FormModelInterface $formModel, string $attribute): self
21
    {
22 74
        $new = clone $this;
23 74
        $new->formModel = $formModel;
24 74
        $new->attribute = $attribute;
25 74
        return $new;
26
    }
27
28 67
    final protected function getFormModel(): FormModelInterface
29
    {
30 67
        if ($this->formModel === null) {
31 1
            throw new InvalidArgumentException('Form model is not set.');
32
        }
33
34 66
        return $this->formModel;
35
    }
36
37 44
    final protected function getAttributeName(): string
38
    {
39 44
        return HtmlForm::getAttributeName($this->getFormModel(), $this->attribute);
40
    }
41
42
    /**
43
     * @return bool|float|int|iterable|object|string|Stringable|null
44
     */
45 29
    final protected function getAttributeValue()
46
    {
47 29
        return HtmlForm::getAttributeValue($this->getFormModel(), $this->attribute);
48
    }
49
50 36
    final protected function getAttributeLabel(): string
51
    {
52 36
        return HtmlForm::getAttributeLabel($this->getFormModel(), $this->attribute);
53
    }
54
55 37
    final protected function getAttributeHint(): string
56
    {
57 37
        return HtmlForm::getAttributeHint($this->getFormModel(), $this->attribute);
58
    }
59
60 24
    final protected function getAttributePlaceholder(): ?string
61
    {
62 24
        $placeholder = $this->getFormModel()->getAttributePlaceholder($this->getAttributeName());
63 24
        return $placeholder === '' ? null : $placeholder;
64
    }
65
66 32
    final protected function getInputId(): string
67
    {
68 32
        return HtmlForm::getInputId($this->getFormModel(), $this->attribute);
69
    }
70
71 44
    final protected function getFirstError(): ?string
72
    {
73 44
        return $this->getFormModel()->getFormErrors()->getFirstError($this->getAttributeName());
74
    }
75
}
76