Passed
Pull Request — master (#192)
by Sergei
19:23 queued 16:27
created

FormAttributeTrait::getFormModel()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2.0625

Importance

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