Passed
Pull Request — master (#192)
by Sergei
03:07
created

Url::beforeRender()   C

Complexity

Conditions 14
Paths 102

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 14

Importance

Changes 0
Metric Value
cc 14
eloc 24
c 0
b 0
f 0
nc 102
nop 0
dl 0
loc 38
ccs 25
cts 25
cp 1
crap 14
rs 6.25

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