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

FormAttributeTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 59
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
c 1
b 0
f 0
dl 0
loc 59
ccs 24
cts 24
cp 1
rs 10
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
    /**
17
     * @return static
18
     */
19 103
    final public function attribute(FormModelInterface $formModel, string $attribute): self
20
    {
21 103
        $new = clone $this;
22 103
        $new->formModel = $formModel;
23 103
        $new->attribute = $attribute;
24 103
        return $new;
25
    }
26
27 95
    final protected function getFormModel(): FormModelInterface
28
    {
29 95
        if ($this->formModel === null) {
30 1
            throw new InvalidArgumentException('Form model is not set.');
31
        }
32
33 94
        return $this->formModel;
34
    }
35
36 73
    final protected function getAttributeName(): string
37
    {
38 73
        return HtmlForm::getAttributeName($this->getFormModel(), $this->attribute);
39
    }
40
41 60
    final protected function getAttributeValue(): mixed
42
    {
43 60
        return HtmlForm::getAttributeValue($this->getFormModel(), $this->attribute);
44
    }
45
46 63
    final protected function getAttributeLabel(): string
47
    {
48 63
        return HtmlForm::getAttributeLabel($this->getFormModel(), $this->attribute);
49
    }
50
51 66
    final protected function getAttributeHint(): string
52
    {
53 66
        return HtmlForm::getAttributeHint($this->getFormModel(), $this->attribute);
54
    }
55
56 29
    final protected function getAttributePlaceholder(): ?string
57
    {
58 29
        $placeholder = $this->getFormModel()->getAttributePlaceholder($this->getAttributeName());
59 29
        return $placeholder === '' ? null : $placeholder;
60
    }
61
62 62
    final protected function getInputId(): string
63
    {
64 62
        return HtmlForm::getInputId($this->getFormModel(), $this->attribute);
65
    }
66
67 73
    final protected function getFirstError(): ?string
68
    {
69 73
        return $this->getFormModel()->getFormErrors()->getFirstError($this->getAttributeName());
70
    }
71
}
72