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

Text::beforeRender()   B

Complexity

Conditions 10
Paths 32

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 10

Importance

Changes 0
Metric Value
cc 10
eloc 15
c 0
b 0
f 0
nc 32
nop 0
dl 0
loc 23
ccs 16
cts 16
cp 1
crap 10
rs 7.6666

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 2
    public function ariaDescribedBy(?string $value): self
40
    {
41 2
        $new = clone $this;
42 2
        $new->inputTagAttributes['aria-describedby'] = $value;
43 2
        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 2
    public function ariaLabel(?string $value): self
52
    {
53 2
        $new = clone $this;
54 2
        $new->inputTagAttributes['aria-label'] = $value;
55 2
        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 2
    public function autofocus(bool $value = true): self
65
    {
66 2
        $new = clone $this;
67 2
        $new->inputTagAttributes['autofocus'] = $value;
68 2
        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 2
    public function dirname(?string $value): self
79
    {
80 2
        $new = clone $this;
81 2
        $new->inputTagAttributes['dirname'] = $value;
82 2
        return $new;
83
    }
84
85
    /**
86
     * @link https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#attr-fe-disabled
87
     */
88 2
    public function disabled(bool $disabled = true): self
89
    {
90 2
        $new = clone $this;
91 2
        $new->inputTagAttributes['disabled'] = $disabled;
92 2
        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 2
    public function maxlength(?int $value): self
104
    {
105 2
        $new = clone $this;
106 2
        $new->inputTagAttributes['maxlength'] = $value;
107 2
        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 2
    public function minlength(?int $value): self
119
    {
120 2
        $new = clone $this;
121 2
        $new->inputTagAttributes['minlength'] = $value;
122 2
        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 2
    public function pattern(?string $value): self
133
    {
134 2
        $new = clone $this;
135 2
        $new->inputTagAttributes['pattern'] = $value;
136 2
        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 2
    public function readonly(bool $value = true): self
147
    {
148 2
        $new = clone $this;
149 2
        $new->inputTagAttributes['readonly'] = $value;
150 2
        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 2
    public function required(bool $value = true): self
161
    {
162 2
        $new = clone $this;
163 2
        $new->inputTagAttributes['required'] = $value;
164 2
        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 2
    public function size(?int $value): self
175
    {
176 2
        $new = clone $this;
177 2
        $new->inputTagAttributes['size'] = $value;
178 2
        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 2
    public function tabIndex(?int $value): self
199
    {
200 2
        $new = clone $this;
201 2
        $new->inputTagAttributes['tabindex'] = $value;
202 2
        return $new;
203
    }
204
205
    /**
206
     * @psalm-suppress MixedAssignment,MixedArgument Remove after fix https://github.com/yiisoft/validator/issues/225
207
     */
208 54
    protected function beforeRender(): void
209
    {
210 54
        parent::beforeRender();
211 54
        if ($this->enrichmentFromRules && $this->hasFormModelAndAttribute()) {
212 5
            $rules = $this->getFormModel()->getRules()[$this->getAttributeName()] ?? [];
213 5
            foreach ($rules as $rule) {
214 5
                if ($rule instanceof Required) {
215 2
                    $this->inputTagAttributes['required'] = true;
216
                }
217
218 5
                if ($rule instanceof HasLength) {
219 1
                    if (null !== $min = $rule->getOptions()['min']) {
220 1
                        $this->inputTagAttributes['minlength'] = $min;
221
                    }
222 1
                    if (null !== $max = $rule->getOptions()['max']) {
223 1
                        $this->inputTagAttributes['maxlength'] = $max;
224
                    }
225
                }
226
227 5
                if ($rule instanceof Regex) {
228 2
                    if (!($rule->getOptions()['not'])) {
229 1
                        $this->inputTagAttributes['pattern'] = Html::normalizeRegexpPattern(
230 1
                            $rule->getOptions()['pattern']
231
                        );
232
                    }
233
                }
234
            }
235
        }
236
    }
237
238 54
    protected function generateInput(): string
239
    {
240 54
        $value = $this->getAttributeValue();
241
242 54
        if (!is_string($value) && $value !== null) {
243 1
            throw new InvalidArgumentException('Text field requires a string or null value.');
244
        }
245
246 53
        $tagAttributes = $this->getInputTagAttributes();
247
248 53
        return Html::textInput($this->getInputName(), $value, $tagAttributes)->render();
249
    }
250
251 38
    protected function prepareContainerTagAttributes(array &$attributes): void
252
    {
253 38
        if ($this->hasFormModelAndAttribute()) {
254 38
            $this->addValidationClassToTagAttributes(
255
                $attributes,
256 38
                $this->getFormModel(),
257 38
                $this->getAttributeName(),
258
            );
259
        }
260
    }
261
262 53
    protected function prepareInputTagAttributes(array &$attributes): void
263
    {
264 53
        $this->preparePlaceholderInInputTagAttributes($attributes);
265
    }
266
}
267