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

FormAttributeTrait::getFirstError()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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