Passed
Pull Request — master (#196)
by Rustam
03:00
created

Url::prepareInputAttributes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

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

This check looks for private methods that have been defined, but are not used inside the class.

Loading history...
264
    {
265
        $result = '';
266
267
        for ($i = 0, $length = strlen($scheme); $i < $length; $i++) {
268
            $result .= '[' . strtolower($scheme[$i]) . strtoupper($scheme[$i]) . ']';
269
        }
270
271
        return $result;
272
    }
273
}
274