Passed
Push — master ( 79bb78...087da0 )
by Alexander
02:53
created

Text::beforeRender()   C

Complexity

Conditions 12
Paths 33

Size

Total Lines 27
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 12
eloc 17
c 1
b 0
f 0
nc 33
nop 0
dl 0
loc 27
ccs 18
cts 18
cp 1
crap 12
rs 6.9666

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\BeforeValidationInterface;
17
use Yiisoft\Validator\Rule\HasLength;
18
use Yiisoft\Validator\Rule\Regex;
19
use Yiisoft\Validator\Rule\Required;
0 ignored issues
show
Bug introduced by
The type Yiisoft\Validator\Rule\Required was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

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