Passed
Pull Request — master (#192)
by Alexander
28:18 queued 25:44
created

Number::beforeRender()   B

Complexity

Conditions 8
Paths 12

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 8

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 8
eloc 11
c 1
b 0
f 0
nc 12
nop 0
dl 0
loc 16
ccs 12
cts 12
cp 1
crap 8
rs 8.4444
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 6
    public function max(int|float|string|Stringable|null $value): self
36
    {
37 6
        $new = clone $this;
38 6
        $new->inputTagAttributes['max'] = $value;
39 6
        return $new;
40
    }
41
42
    /**
43
     * @link https://html.spec.whatwg.org/multipage/input.html#attr-input-min
44
     */
45 6
    public function min(int|float|string|Stringable|null $value): self
46
    {
47 6
        $new = clone $this;
48 6
        $new->inputTagAttributes['min'] = $value;
49 6
        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 6
    public function step(float|int|string|Stringable|null $value): self
58
    {
59 6
        $new = clone $this;
60 6
        $new->inputTagAttributes['step'] = $value;
61 6
        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 2
    public function readonly(bool $value = true): self
72
    {
73 2
        $new = clone $this;
74 2
        $new->inputTagAttributes['readonly'] = $value;
75 2
        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 2
    public function required(bool $value = true): self
86
    {
87 2
        $new = clone $this;
88 2
        $new->inputTagAttributes['required'] = $value;
89 2
        return $new;
90
    }
91
92
    /**
93
     * @link https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-disabled
94
     */
95 2
    public function disabled(bool $disabled = true): self
96
    {
97 2
        $new = clone $this;
98 2
        $new->inputTagAttributes['disabled'] = $disabled;
99 2
        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 2
    public function ariaDescribedBy(?string $value): self
108
    {
109 2
        $new = clone $this;
110 2
        $new->inputTagAttributes['aria-describedby'] = $value;
111 2
        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 2
    public function ariaLabel(?string $value): self
120
    {
121 2
        $new = clone $this;
122 2
        $new->inputTagAttributes['aria-label'] = $value;
123 2
        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 2
    public function autofocus(bool $value = true): self
133
    {
134 2
        $new = clone $this;
135 2
        $new->inputTagAttributes['autofocus'] = $value;
136 2
        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 2
    public function tabIndex(?int $value): self
157
    {
158 2
        $new = clone $this;
159 2
        $new->inputTagAttributes['tabindex'] = $value;
160 2
        return $new;
161
    }
162
163
    /**
164
     * @psalm-suppress MixedAssignment,MixedArgument Remove after fix https://github.com/yiisoft/validator/issues/225
165
     */
166 27
    protected function beforeRender(): void
167
    {
168 27
        parent::beforeRender();
169 27
        if ($this->enrichmentFromRules && $this->hasFormModelAndAttribute()) {
170 2
            $rules = $this->getFormModel()->getRules()[$this->getAttributeName()] ?? [];
171 2
            foreach ($rules as $rule) {
172 2
                if ($rule instanceof Required) {
173 1
                    $this->inputTagAttributes['required'] = true;
174
                }
175
176 2
                if ($rule instanceof NumberRule) {
177 1
                    if (null !== $min = $rule->getOptions()['min']) {
178 1
                        $this->inputTagAttributes['min'] = $min;
179
                    }
180 1
                    if (null !== $max = $rule->getOptions()['max']) {
181 1
                        $this->inputTagAttributes['max'] = $max;
182
                    }
183
                }
184
            }
185
        }
186
    }
187
188 27
    protected function generateInput(): string
189
    {
190 27
        $value = $this->getAttributeValue();
191
192 27
        if (!is_numeric($value) && $value !== null) {
193 1
            throw new InvalidArgumentException('Number field requires a numeric or null value.');
194
        }
195
196 26
        $tagAttributes = $this->getInputTagAttributes();
197
198 26
        return Html::input('number', $this->getInputName(), $value, $tagAttributes)->render();
199
    }
200
201 9
    protected function prepareContainerTagAttributes(array &$attributes): void
202
    {
203 9
        if ($this->hasFormModelAndAttribute()) {
204 9
            $this->addValidationClassToTagAttributes(
205
                $attributes,
206 9
                $this->getFormModel(),
207 9
                $this->getAttributeName(),
208
            );
209
        }
210
    }
211
212 26
    protected function prepareInputTagAttributes(array &$attributes): void
213
    {
214 26
        $this->preparePlaceholderInInputTagAttributes($attributes);
215
    }
216
}
217