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

Text::beforeRender()   B

Complexity

Conditions 10
Paths 32

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 15
nc 32
nop 0
dl 0
loc 23
rs 7.6666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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