Passed
Pull Request — master (#192)
by Alexander
05:47 queued 02:55
created

Range::ariaLabel()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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