Test Failed
Pull Request — master (#192)
by Sergei
02:42
created

Number::prepareInputAttributes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Form\Field;
6
7
use InvalidArgumentException;
8
use Stringable;
9
use Yiisoft\Form\Field\Base\EnrichmentFromRules\EnrichmentFromRulesInterface;
10
use Yiisoft\Form\Field\Base\EnrichmentFromRules\EnrichmentFromRulesTrait;
11
use Yiisoft\Form\Field\Base\InputField;
12
use Yiisoft\Form\Field\Base\Placeholder\PlaceholderInterface;
13
use Yiisoft\Form\Field\Base\Placeholder\PlaceholderTrait;
14
use Yiisoft\Form\Field\Base\ValidationClass\ValidationClassInterface;
15
use Yiisoft\Form\Field\Base\ValidationClass\ValidationClassTrait;
16
use Yiisoft\Html\Html;
17
use Yiisoft\Validator\Rule\Number as NumberRule;
18
use Yiisoft\Validator\Rule\Required;
19
20
/**
21
 * Represents `<input>` element of type "number" are used to let the user enter and edit a telephone number.
22
 *
23
 * @link https://html.spec.whatwg.org/multipage/input.html#number-state-(type=number)
24
 * @link https://developer.mozilla.org/docs/Web/HTML/Element/input/number
25
 */
26
final class Number extends InputField implements EnrichmentFromRulesInterface, PlaceholderInterface, ValidationClassInterface
27
{
28
    use EnrichmentFromRulesTrait;
29
    use PlaceholderTrait;
30
    use ValidationClassTrait;
31
32
    /**
33
     * @link https://html.spec.whatwg.org/multipage/input.html#attr-input-max
34
     */
35
    public function max(int|float|string|Stringable|null $value): self
36
    {
37
        $new = clone $this;
38
        $new->inputAttributes['max'] = $value;
39
        return $new;
40
    }
41
42
    /**
43
     * @link https://html.spec.whatwg.org/multipage/input.html#attr-input-min
44
     */
45
    public function min(int|float|string|Stringable|null $value): self
46
    {
47
        $new = clone $this;
48
        $new->inputAttributes['min'] = $value;
49
        return $new;
50
    }
51
52
    /**
53
     * Granularity to be matched by the form control's value.
54
     *
55
     * @link https://html.spec.whatwg.org/multipage/input.html#attr-input-step
56
     */
57
    public function step(float|int|string|Stringable|null $value): self
58
    {
59
        $new = clone $this;
60
        $new->inputAttributes['step'] = $value;
61
        return $new;
62
    }
63
64
    /**
65
     * A boolean attribute that controls whether or not the user can edit the form control.
66
     *
67
     * @param bool $value Whether to allow the value to be edited by the user.
68
     *
69
     * @link https://html.spec.whatwg.org/multipage/input.html#attr-input-readonly
70
     */
71
    public function readonly(bool $value = true): self
72
    {
73
        $new = clone $this;
74
        $new->inputAttributes['readonly'] = $value;
75
        return $new;
76
    }
77
78
    /**
79
     * A boolean attribute. When specified, the element is required.
80
     *
81
     * @param bool $value Whether the control is required for form submission.
82
     *
83
     * @link https://html.spec.whatwg.org/multipage/input.html#attr-input-required
84
     */
85
    public function required(bool $value = true): self
86
    {
87
        $new = clone $this;
88
        $new->inputAttributes['required'] = $value;
89
        return $new;
90
    }
91
92
    /**
93
     * @link https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-disabled
94
     */
95
    public function disabled(bool $disabled = true): self
96
    {
97
        $new = clone $this;
98
        $new->inputAttributes['disabled'] = $disabled;
99
        return $new;
100
    }
101
102
    /**
103
     * Identifies the element (or elements) that describes the object.
104
     *
105
     * @link https://w3c.github.io/aria/#aria-describedby
106
     */
107
    public function ariaDescribedBy(?string $value): self
108
    {
109
        $new = clone $this;
110
        $new->inputAttributes['aria-describedby'] = $value;
111
        return $new;
112
    }
113
114
    /**
115
     * Defines a string value that labels the current element.
116
     *
117
     * @link https://w3c.github.io/aria/#aria-label
118
     */
119
    public function ariaLabel(?string $value): self
120
    {
121
        $new = clone $this;
122
        $new->inputAttributes['aria-label'] = $value;
123
        return $new;
124
    }
125
126
    /**
127
     * Focus on the control (put cursor into it) when the page loads. Only one form element could be in focus
128
     * at the same time.
129
     *
130
     * @link https://html.spec.whatwg.org/multipage/interaction.html#attr-fe-autofocus
131
     */
132
    public function autofocus(bool $value = true): self
133
    {
134
        $new = clone $this;
135
        $new->inputAttributes['autofocus'] = $value;
136
        return $new;
137
    }
138
139
    /**
140
     * The `tabindex` attribute indicates that its element can be focused, and where it participates in sequential
141
     * keyboard navigation (usually with the Tab key, hence the name).
142
     *
143
     * It accepts an integer as a value, with different results depending on the integer's value:
144
     *
145
     * - A negative value (usually `tabindex="-1"`) means that the element is not reachable via sequential keyboard
146
     *   navigation, but could be focused with Javascript or visually. It's mostly useful to create accessible widgets
147
     *   with JavaScript.
148
     * - `tabindex="0"` means that the element should be focusable in sequential keyboard navigation, but its order is
149
     *   defined by the document's source order.
150
     * - A positive value means the element should be focusable in sequential keyboard navigation, with its order
151
     *   defined by the value of the number. That is, `tabindex="4"` is focused before `tabindex="5"`, but after
152
     *   `tabindex="3"`.
153
     *
154
     * @link https://html.spec.whatwg.org/multipage/interaction.html#attr-tabindex
155
     */
156
    public function tabIndex(?int $value): self
157
    {
158
        $new = clone $this;
159
        $new->inputAttributes['tabindex'] = $value;
160
        return $new;
161
    }
162
163
    /**
164
     * @psalm-suppress MixedAssignment,MixedArgument Remove after fix https://github.com/yiisoft/validator/issues/225
165
     */
166
    protected function beforeRender(): void
167
    {
168
        parent::beforeRender();
169
        if ($this->enrichmentFromRules && $this->hasFormModelAndAttribute()) {
170
            $rules = $this->getFormModel()->getRules()[$this->getFormAttributeName()] ?? [];
171
            foreach ($rules as $rule) {
172
                if ($rule instanceof Required) {
173
                    $this->inputAttributes['required'] = true;
174
                }
175
176
                if ($rule instanceof NumberRule) {
177
                    if (null !== $min = $rule->getOptions()['min']) {
178
                        $this->inputAttributes['min'] = $min;
179
                    }
180
                    if (null !== $max = $rule->getOptions()['max']) {
181
                        $this->inputAttributes['max'] = $max;
182
                    }
183
                }
184
            }
185
        }
186
    }
187
188
    protected function generateInput(): string
189
    {
190
        $value = $this->getFormAttributeValue();
191
192
        if (!is_numeric($value) && $value !== null) {
193
            throw new InvalidArgumentException('Number field requires a numeric or null value.');
194
        }
195
196
        $inputAttributes = $this->getInputAttributes();
197
198
        return Html::input('number', $this->getInputName(), $value, $inputAttributes)->render();
199
    }
200
201
    protected function prepareContainerAttributes(array &$attributes): void
202
    {
203
        if ($this->hasFormModelAndAttribute()) {
204
            $this->addValidationClassToAttributes(
205
                $attributes,
206
                $this->getFormModel(),
207
                $this->getFormAttributeName(),
208
            );
209
        }
210
    }
211
212
    protected function prepareInputAttributes(array &$attributes): void
213
    {
214
        $this->preparePlaceholderInInputAttributes($attributes);
215
    }
216
}
217