Test Failed
Pull Request — master (#159)
by Alexander
02:49
created

FormAttributeTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 18
dl 0
loc 62
rs 10
c 1
b 0
f 0
wmc 11

9 Methods

Rating   Name   Duplication   Size   Complexity  
A getFormModel() 0 7 2
A attribute() 0 6 1
A getFirstError() 0 3 1
A getAttributeValue() 0 3 1
A getAttributeHint() 0 3 1
A getInputId() 0 3 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
    final public function attribute(FormModelInterface $formModel, string $attribute): self
21
    {
22
        $new = clone $this;
23
        $new->formModel = $formModel;
24
        $new->attribute = $attribute;
25
        return $new;
26
    }
27
28
    final protected function getFormModel(): FormModelInterface
29
    {
30
        if ($this->formModel === null) {
31
            throw new InvalidArgumentException('Form model is not set.');
32
        }
33
34
        return $this->formModel;
35
    }
36
37
    final protected function getAttributeName(): string
38
    {
39
        return HtmlForm::getAttributeName($this->getFormModel(), $this->attribute);
40
    }
41
42
    /**
43
     * @return bool|float|int|iterable|object|string|Stringable|null
44
     */
45
    final protected function getAttributeValue()
46
    {
47
        return HtmlForm::getAttributeValue($this->getFormModel(), $this->attribute);
48
    }
49
50
    final protected function getAttributeLabel(): string
51
    {
52
        return HtmlForm::getAttributeLabel($this->getFormModel(), $this->attribute);
53
    }
54
55
    final protected function getAttributeHint(): string
56
    {
57
        return HtmlForm::getAttributeHint($this->getFormModel(), $this->attribute);
58
    }
59
60
    final protected function getAttributePlaceholder(): ?string
61
    {
62
        $placeholder = $this->getFormModel()->getAttributePlaceholder($this->getAttributeName());
63
        return $placeholder === '' ? null : $placeholder;
64
    }
65
66
    final protected function getInputId(): string
67
    {
68
        return HtmlForm::getInputId($this->getFormModel(), $this->attribute);
69
    }
70
71
    final protected function getFirstError(): ?string
72
    {
73
        return $this->getFormModel()->getFormErrors()->getFirstError($this->getAttributeName());
74
    }
75
}
76