Passed
Push — fix-php-74 ( 9989b6...f6eb65 )
by Alexander
30:32 queued 19s
created

BaseHtml   F

Complexity

Total Complexity 271

Size/Duplication

Total Lines 2306
Duplicated Lines 0 %

Test Coverage

Coverage 97.95%

Importance

Changes 0
Metric Value
eloc 574
dl 0
loc 2306
ccs 573
cts 585
cp 0.9795
rs 2
c 0
b 0
f 0
wmc 271

73 Methods

Rating   Name   Duplication   Size   Complexity  
A tag() 0 7 4
B activeBooleanInput() 0 26 8
A activeListInput() 0 12 5
A encode() 0 3 2
A mailto() 0 4 2
A textarea() 0 5 1
A activeDropDownList() 0 7 2
C radioList() 0 47 12
A dropDownList() 0 9 2
A checkbox() 0 3 1
A activeRadioList() 0 3 1
A setActivePlaceholder() 0 5 3
A activeHiddenInput() 0 3 1
F renderSelectOptions() 0 56 20
A activeTextInput() 0 3 1
A activeCheckboxList() 0 3 1
A textInput() 0 3 1
A cssFile() 0 17 5
A resetButton() 0 4 1
F checkboxList() 0 53 14
A fileInput() 0 3 1
A wrapIntoCondition() 0 7 2
C beginForm() 0 44 12
B listBox() 0 26 9
A activePasswordInput() 0 3 1
A endTag() 0 7 3
A endForm() 0 3 1
A jsFile() 0 10 2
A script() 0 3 1
A activeFileInput() 0 19 3
A radio() 0 3 1
A collectErrors() 0 22 5
A activeHint() 0 10 3
A a() 0 7 2
A activeInput() 0 12 4
A decode() 0 3 1
A activeTextarea() 0 15 4
A passwordInput() 0 3 1
A activeCheckbox() 0 3 1
A resetInput() 0 5 1
A ol() 0 4 1
A submitInput() 0 5 1
A hiddenInput() 0 3 1
A beginTag() 0 7 3
A submitButton() 0 4 1
A button() 0 7 2
A errorSummary() 0 17 4
A csrfMetaTags() 0 9 3
A buttonInput() 0 5 1
A activeLabel() 0 6 1
A style() 0 3 1
A normalizeMaxLength() 0 9 6
A ul() 0 25 5
A error() 0 12 3
A activeRadio() 0 3 1
A img() 0 17 5
A input() 0 8 3
A label() 0 4 1
A activeListBox() 0 3 1
B booleanInput() 0 31 8
B addCssStyle() 0 15 8
A getInputId() 0 5 2
A escapeJsRegularExpression() 0 16 3
A mergeCssClasses() 0 11 5
A getAttributeName() 0 7 2
A cssStyleToArray() 0 11 3
A removeCssStyle() 0 8 4
A cssStyleFromArray() 0 8 3
A addCssClass() 0 11 3
A removeCssClass() 0 17 5
D renderTagAttributes() 0 50 18
C getAttributeValue() 0 32 13
A getInputName() 0 16 5

How to fix   Complexity   

Complex Class

Complex classes like BaseHtml often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use BaseHtml, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\helpers;
9
10
use Yii;
11
use yii\base\InvalidArgumentException;
12
use yii\base\Model;
13
use yii\db\ActiveRecordInterface;
14
use yii\validators\StringValidator;
15
use yii\web\Request;
16
17
/**
18
 * BaseHtml provides concrete implementation for [[Html]].
19
 *
20
 * Do not use BaseHtml. Use [[Html]] instead.
21
 *
22
 * @author Qiang Xue <[email protected]>
23
 * @since 2.0
24
 */
25
class BaseHtml
26
{
27
    /**
28
     * @var string Regular expression used for attribute name validation.
29
     * @since 2.0.12
30
     */
31
    public static $attributeRegex = '/(^|.*\])([\w\.\+]+)(\[.*|$)/u';
32
    /**
33
     * @var array list of void elements (element name => 1)
34
     * @see http://www.w3.org/TR/html-markup/syntax.html#void-element
35
     */
36
    public static $voidElements = [
37
        'area' => 1,
38
        'base' => 1,
39
        'br' => 1,
40
        'col' => 1,
41
        'command' => 1,
42
        'embed' => 1,
43
        'hr' => 1,
44
        'img' => 1,
45
        'input' => 1,
46
        'keygen' => 1,
47
        'link' => 1,
48
        'meta' => 1,
49
        'param' => 1,
50
        'source' => 1,
51
        'track' => 1,
52
        'wbr' => 1,
53
    ];
54
    /**
55
     * @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes
56
     * that are rendered by [[renderTagAttributes()]].
57
     */
58
    public static $attributeOrder = [
59
        'type',
60
        'id',
61
        'class',
62
        'name',
63
        'value',
64
65
        'href',
66
        'src',
67
        'srcset',
68
        'form',
69
        'action',
70
        'method',
71
72
        'selected',
73
        'checked',
74
        'readonly',
75
        'disabled',
76
        'multiple',
77
78
        'size',
79
        'maxlength',
80
        'width',
81
        'height',
82
        'rows',
83
        'cols',
84
85
        'alt',
86
        'title',
87
        'rel',
88
        'media',
89
    ];
90
    /**
91
     * @var array list of tag attributes that should be specially handled when their values are of array type.
92
     * In particular, if the value of the `data` attribute is `['name' => 'xyz', 'age' => 13]`, two attributes
93
     * will be generated instead of one: `data-name="xyz" data-age="13"`.
94
     * @since 2.0.3
95
     */
96
    public static $dataAttributes = ['data', 'data-ng', 'ng'];
97
98
99
    /**
100
     * Encodes special characters into HTML entities.
101
     * The [[\yii\base\Application::charset|application charset]] will be used for encoding.
102
     * @param string $content the content to be encoded
103
     * @param bool $doubleEncode whether to encode HTML entities in `$content`. If false,
104
     * HTML entities in `$content` will not be further encoded.
105
     * @return string the encoded content
106
     * @see decode()
107
     * @see https://secure.php.net/manual/en/function.htmlspecialchars.php
108
     */
109 229
    public static function encode($content, $doubleEncode = true)
110
    {
111 229
        return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode);
112
    }
113
114
    /**
115
     * Decodes special HTML entities back to the corresponding characters.
116
     * This is the opposite of [[encode()]].
117
     * @param string $content the content to be decoded
118
     * @return string the decoded content
119
     * @see encode()
120
     * @see https://secure.php.net/manual/en/function.htmlspecialchars-decode.php
121
     */
122 1
    public static function decode($content)
123
    {
124 1
        return htmlspecialchars_decode($content, ENT_QUOTES);
125
    }
126
127
    /**
128
     * Generates a complete HTML tag.
129
     * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
130
     * @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded.
131
     * If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks.
132
     * @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs.
133
     * These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
134
     * If a value is null, the corresponding attribute will not be rendered.
135
     *
136
     * For example when using `['class' => 'my-class', 'target' => '_blank', 'value' => null]` it will result in the
137
     * html attributes rendered like this: `class="my-class" target="_blank"`.
138
     *
139
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
140
     *
141
     * @return string the generated HTML tag
142
     * @see beginTag()
143
     * @see endTag()
144
     */
145 215
    public static function tag($name, $content = '', $options = [])
146
    {
147 215
        if ($name === null || $name === false) {
148 3
            return $content;
149
        }
150 214
        $html = "<$name" . static::renderTagAttributes($options) . '>';
151 214
        return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>";
0 ignored issues
show
Bug introduced by
It seems like $name can also be of type true; however, parameter $str of strtolower() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

151
        return isset(static::$voidElements[strtolower(/** @scrutinizer ignore-type */ $name)]) ? $html : "$html$content</$name>";
Loading history...
152
    }
153
154
    /**
155
     * Generates a start tag.
156
     * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
157
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
158
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
159
     * If a value is null, the corresponding attribute will not be rendered.
160
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
161
     * @return string the generated start tag
162
     * @see endTag()
163
     * @see tag()
164
     */
165 49
    public static function beginTag($name, $options = [])
166
    {
167 49
        if ($name === null || $name === false) {
168 3
            return '';
169
        }
170
171 49
        return "<$name" . static::renderTagAttributes($options) . '>';
172
    }
173
174
    /**
175
     * Generates an end tag.
176
     * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
177
     * @return string the generated end tag
178
     * @see beginTag()
179
     * @see tag()
180
     */
181 16
    public static function endTag($name)
182
    {
183 16
        if ($name === null || $name === false) {
184 3
            return '';
185
        }
186
187 15
        return "</$name>";
188
    }
189
190
    /**
191
     * Generates a style tag.
192
     * @param string $content the style content
193
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
194
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
195
     * If a value is null, the corresponding attribute will not be rendered.
196
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
197
     * @return string the generated style tag
198
     */
199 1
    public static function style($content, $options = [])
200
    {
201 1
        return static::tag('style', $content, $options);
202
    }
203
204
    /**
205
     * Generates a script tag.
206
     * @param string $content the script content
207
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
208
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
209
     * If a value is null, the corresponding attribute will not be rendered.
210
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
211
     * @return string the generated script tag
212
     */
213 2
    public static function script($content, $options = [])
214
    {
215 2
        return static::tag('script', $content, $options);
216
    }
217
218
    /**
219
     * Generates a link tag that refers to an external CSS file.
220
     * @param array|string $url the URL of the external CSS file. This parameter will be processed by [[Url::to()]].
221
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
222
     *
223
     * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
224
     *   the generated `link` tag will be enclosed within the conditional comments. This is mainly useful
225
     *   for supporting old versions of IE browsers.
226
     * - noscript: if set to true, `link` tag will be wrapped into `<noscript>` tags.
227
     *
228
     * The rest of the options will be rendered as the attributes of the resulting link tag. The values will
229
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
230
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
231
     * @return string the generated link tag
232
     * @see Url::to()
233
     */
234 21
    public static function cssFile($url, $options = [])
235
    {
236 21
        if (!isset($options['rel'])) {
237 21
            $options['rel'] = 'stylesheet';
238
        }
239 21
        $options['href'] = Url::to($url);
240
241 21
        if (isset($options['condition'])) {
242 1
            $condition = $options['condition'];
243 1
            unset($options['condition']);
244 1
            return self::wrapIntoCondition(static::tag('link', '', $options), $condition);
245 21
        } elseif (isset($options['noscript']) && $options['noscript'] === true) {
246 1
            unset($options['noscript']);
247 1
            return '<noscript>' . static::tag('link', '', $options) . '</noscript>';
248
        }
249
250 21
        return static::tag('link', '', $options);
251
    }
252
253
    /**
254
     * Generates a script tag that refers to an external JavaScript file.
255
     * @param string $url the URL of the external JavaScript file. This parameter will be processed by [[Url::to()]].
256
     * @param array $options the tag options in terms of name-value pairs. The following option is specially handled:
257
     *
258
     * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
259
     *   the generated `script` tag will be enclosed within the conditional comments. This is mainly useful
260
     *   for supporting old versions of IE browsers.
261
     *
262
     * The rest of the options will be rendered as the attributes of the resulting script tag. The values will
263
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
264
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
265
     * @return string the generated script tag
266
     * @see Url::to()
267
     */
268 24
    public static function jsFile($url, $options = [])
269
    {
270 24
        $options['src'] = Url::to($url);
271 24
        if (isset($options['condition'])) {
272 1
            $condition = $options['condition'];
273 1
            unset($options['condition']);
274 1
            return self::wrapIntoCondition(static::tag('script', '', $options), $condition);
275
        }
276
277 24
        return static::tag('script', '', $options);
278
    }
279
280
    /**
281
     * Wraps given content into conditional comments for IE, e.g., `lt IE 9`.
282
     * @param string $content raw HTML content.
283
     * @param string $condition condition string.
284
     * @return string generated HTML.
285
     */
286 2
    private static function wrapIntoCondition($content, $condition)
287
    {
288 2
        if (strpos($condition, '!IE') !== false) {
289 2
            return "<!--[if $condition]><!-->\n" . $content . "\n<!--<![endif]-->";
290
        }
291
292 2
        return "<!--[if $condition]>\n" . $content . "\n<![endif]-->";
293
    }
294
295
    /**
296
     * Generates the meta tags containing CSRF token information.
297
     * @return string the generated meta tags
298
     * @see Request::enableCsrfValidation
299
     */
300 4
    public static function csrfMetaTags()
301
    {
302 4
        $request = Yii::$app->getRequest();
303 4
        if ($request instanceof Request && $request->enableCsrfValidation) {
304 3
            return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n"
305 3
                . static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n";
306
        }
307
308 1
        return '';
309
    }
310
311
    /**
312
     * Generates a form start tag.
313
     * @param array|string $action the form action URL. This parameter will be processed by [[Url::to()]].
314
     * @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive).
315
     * Since most browsers only support "post" and "get", if other methods are given, they will
316
     * be simulated using "post", and a hidden input will be added which contains the actual method type.
317
     * See [[\yii\web\Request::methodParam]] for more details.
318
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
319
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
320
     * If a value is null, the corresponding attribute will not be rendered.
321
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
322
     *
323
     * Special options:
324
     *
325
     *  - `csrf`: whether to generate the CSRF hidden input. Defaults to true.
326
     *
327
     * @return string the generated form start tag.
328
     * @see endForm()
329
     */
330 46
    public static function beginForm($action = '', $method = 'post', $options = [])
331
    {
332 46
        $action = Url::to($action);
333
334 46
        $hiddenInputs = [];
335
336 46
        $request = Yii::$app->getRequest();
337 46
        if ($request instanceof Request) {
338 41
            if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) {
339
                // simulate PUT, DELETE, etc. via POST
340 4
                $hiddenInputs[] = static::hiddenInput($request->methodParam, $method);
341 4
                $method = 'post';
342
            }
343 41
            $csrf = ArrayHelper::remove($options, 'csrf', true);
344
345 41
            if ($csrf && $request->enableCsrfValidation && strcasecmp($method, 'post') === 0) {
346 34
                $hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken());
347
            }
348
        }
349
350 46
        if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) {
351
            // query parameters in the action are ignored for GET method
352
            // we use hidden fields to add them back
353 1
            foreach (explode('&', substr($action, $pos + 1)) as $pair) {
354 1
                if (($pos1 = strpos($pair, '=')) !== false) {
355 1
                    $hiddenInputs[] = static::hiddenInput(
356 1
                        urldecode(substr($pair, 0, $pos1)),
357 1
                        urldecode(substr($pair, $pos1 + 1))
358
                    );
359
                } else {
360 1
                    $hiddenInputs[] = static::hiddenInput(urldecode($pair), '');
361
                }
362
            }
363 1
            $action = substr($action, 0, $pos);
364
        }
365
366 46
        $options['action'] = $action;
367 46
        $options['method'] = $method;
368 46
        $form = static::beginTag('form', $options);
369 46
        if (!empty($hiddenInputs)) {
370 39
            $form .= "\n" . implode("\n", $hiddenInputs);
371
        }
372
373 46
        return $form;
374
    }
375
376
    /**
377
     * Generates a form end tag.
378
     * @return string the generated tag
379
     * @see beginForm()
380
     */
381 39
    public static function endForm()
382
    {
383 39
        return '</form>';
384
    }
385
386
    /**
387
     * Generates a hyperlink tag.
388
     * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
389
     * such as an image tag. If this is coming from end users, you should consider [[encode()]]
390
     * it to prevent XSS attacks.
391
     * @param array|string|null $url the URL for the hyperlink tag. This parameter will be processed by [[Url::to()]]
392
     * and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute
393
     * will not be generated.
394
     *
395
     * If you want to use an absolute url you can call [[Url::to()]] yourself, before passing the URL to this method,
396
     * like this:
397
     *
398
     * ```php
399
     * Html::a('link text', Url::to($url, true))
400
     * ```
401
     *
402
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
403
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
404
     * If a value is null, the corresponding attribute will not be rendered.
405
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
406
     * @return string the generated hyperlink
407
     * @see \yii\helpers\Url::to()
408
     */
409 17
    public static function a($text, $url = null, $options = [])
410
    {
411 17
        if ($url !== null) {
412 17
            $options['href'] = Url::to($url);
413
        }
414
415 17
        return static::tag('a', $text, $options);
416
    }
417
418
    /**
419
     * Generates a mailto hyperlink.
420
     * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
421
     * such as an image tag. If this is coming from end users, you should consider [[encode()]]
422
     * it to prevent XSS attacks.
423
     * @param string $email email address. If this is null, the first parameter (link body) will be treated
424
     * as the email address and used.
425
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
426
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
427
     * If a value is null, the corresponding attribute will not be rendered.
428
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
429
     * @return string the generated mailto link
430
     */
431 2
    public static function mailto($text, $email = null, $options = [])
432
    {
433 2
        $options['href'] = 'mailto:' . ($email === null ? $text : $email);
434 2
        return static::tag('a', $text, $options);
435
    }
436
437
    /**
438
     * Generates an image tag.
439
     * @param array|string $src the image URL. This parameter will be processed by [[Url::to()]].
440
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
441
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
442
     * If a value is null, the corresponding attribute will not be rendered.
443
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
444
     *
445
     * Since version 2.0.12 It is possible to pass the `srcset` option as an array which keys are
446
     * descriptors and values are URLs. All URLs will be processed by [[Url::to()]].
447
     * @return string the generated image tag.
448
     */
449 10
    public static function img($src, $options = [])
450
    {
451 10
        $options['src'] = Url::to($src);
452
453 10
        if (isset($options['srcset']) && is_array($options['srcset'])) {
454 5
            $srcset = [];
455 5
            foreach ($options['srcset'] as $descriptor => $url) {
456 4
                $srcset[] = Url::to($url) . ' ' . $descriptor;
457
            }
458 5
            $options['srcset'] = implode(',', $srcset);
459
        }
460
461 10
        if (!isset($options['alt'])) {
462 9
            $options['alt'] = '';
463
        }
464
465 10
        return static::tag('img', '', $options);
466
    }
467
468
    /**
469
     * Generates a label tag.
470
     * @param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code
471
     * such as an image tag. If this is is coming from end users, you should [[encode()]]
472
     * it to prevent XSS attacks.
473
     * @param string $for the ID of the HTML element that this label is associated with.
474
     * If this is null, the "for" attribute will not be generated.
475
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
476
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
477
     * If a value is null, the corresponding attribute will not be rendered.
478
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
479
     * @return string the generated label tag
480
     */
481 25
    public static function label($content, $for = null, $options = [])
482
    {
483 25
        $options['for'] = $for;
484 25
        return static::tag('label', $content, $options);
485
    }
486
487
    /**
488
     * Generates a button tag.
489
     * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
490
     * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
491
     * you should consider [[encode()]] it to prevent XSS attacks.
492
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
493
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
494
     * If a value is null, the corresponding attribute will not be rendered.
495
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
496
     * @return string the generated button tag
497
     */
498 3
    public static function button($content = 'Button', $options = [])
499
    {
500 3
        if (!isset($options['type'])) {
501 1
            $options['type'] = 'button';
502
        }
503
504 3
        return static::tag('button', $content, $options);
505
    }
506
507
    /**
508
     * Generates a submit button tag.
509
     *
510
     * Be careful when naming form elements such as submit buttons. According to the [jQuery documentation](https://api.jquery.com/submit/) there
511
     * are some reserved names that can cause conflicts, e.g. `submit`, `length`, or `method`.
512
     *
513
     * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
514
     * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
515
     * you should consider [[encode()]] it to prevent XSS attacks.
516
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
517
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
518
     * If a value is null, the corresponding attribute will not be rendered.
519
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
520
     * @return string the generated submit button tag
521
     */
522 1
    public static function submitButton($content = 'Submit', $options = [])
523
    {
524 1
        $options['type'] = 'submit';
525 1
        return static::button($content, $options);
526
    }
527
528
    /**
529
     * Generates a reset button tag.
530
     * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
531
     * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
532
     * you should consider [[encode()]] it to prevent XSS attacks.
533
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
534
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
535
     * If a value is null, the corresponding attribute will not be rendered.
536
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
537
     * @return string the generated reset button tag
538
     */
539 1
    public static function resetButton($content = 'Reset', $options = [])
540
    {
541 1
        $options['type'] = 'reset';
542 1
        return static::button($content, $options);
543
    }
544
545
    /**
546
     * Generates an input type of the given type.
547
     * @param string $type the type attribute.
548
     * @param string $name the name attribute. If it is null, the name attribute will not be generated.
549
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
550
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
551
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
552
     * If a value is null, the corresponding attribute will not be rendered.
553
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
554
     * @return string the generated input tag
555
     */
556 86
    public static function input($type, $name = null, $value = null, $options = [])
557
    {
558 86
        if (!isset($options['type'])) {
559 86
            $options['type'] = $type;
560
        }
561 86
        $options['name'] = $name;
562 86
        $options['value'] = $value === null ? null : (string) $value;
563 86
        return static::tag('input', '', $options);
564
    }
565
566
    /**
567
     * Generates an input button.
568
     * @param string $label the value attribute. If it is null, the value attribute will not be generated.
569
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
570
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
571
     * If a value is null, the corresponding attribute will not be rendered.
572
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
573
     * @return string the generated button tag
574
     */
575 1
    public static function buttonInput($label = 'Button', $options = [])
576
    {
577 1
        $options['type'] = 'button';
578 1
        $options['value'] = $label;
579 1
        return static::tag('input', '', $options);
580
    }
581
582
    /**
583
     * Generates a submit input button.
584
     *
585
     * Be careful when naming form elements such as submit buttons. According to the [jQuery documentation](https://api.jquery.com/submit/) there
586
     * are some reserved names that can cause conflicts, e.g. `submit`, `length`, or `method`.
587
     *
588
     * @param string $label the value attribute. If it is null, the value attribute will not be generated.
589
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
590
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
591
     * If a value is null, the corresponding attribute will not be rendered.
592
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
593
     * @return string the generated button tag
594
     */
595 1
    public static function submitInput($label = 'Submit', $options = [])
596
    {
597 1
        $options['type'] = 'submit';
598 1
        $options['value'] = $label;
599 1
        return static::tag('input', '', $options);
600
    }
601
602
    /**
603
     * Generates a reset input button.
604
     * @param string $label the value attribute. If it is null, the value attribute will not be generated.
605
     * @param array $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]].
606
     * Attributes whose value is null will be ignored and not put in the tag returned.
607
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
608
     * @return string the generated button tag
609
     */
610 1
    public static function resetInput($label = 'Reset', $options = [])
611
    {
612 1
        $options['type'] = 'reset';
613 1
        $options['value'] = $label;
614 1
        return static::tag('input', '', $options);
615
    }
616
617
    /**
618
     * Generates a text input field.
619
     * @param string $name the name attribute.
620
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
621
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
622
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
623
     * If a value is null, the corresponding attribute will not be rendered.
624
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
625
     * @return string the generated text input tag
626
     */
627 1
    public static function textInput($name, $value = null, $options = [])
628
    {
629 1
        return static::input('text', $name, $value, $options);
630
    }
631
632
    /**
633
     * Generates a hidden input field.
634
     * @param string $name the name attribute.
635
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
636
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
637
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
638
     * If a value is null, the corresponding attribute will not be rendered.
639
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
640
     * @return string the generated hidden input tag
641
     */
642 53
    public static function hiddenInput($name, $value = null, $options = [])
643
    {
644 53
        return static::input('hidden', $name, $value, $options);
645
    }
646
647
    /**
648
     * Generates a password input field.
649
     * @param string $name the name attribute.
650
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
651
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
652
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
653
     * If a value is null, the corresponding attribute will not be rendered.
654
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
655
     * @return string the generated password input tag
656
     */
657 1
    public static function passwordInput($name, $value = null, $options = [])
658
    {
659 1
        return static::input('password', $name, $value, $options);
660
    }
661
662
    /**
663
     * Generates a file input field.
664
     * To use a file input field, you should set the enclosing form's "enctype" attribute to
665
     * be "multipart/form-data". After the form is submitted, the uploaded file information
666
     * can be obtained via $_FILES[$name] (see PHP documentation).
667
     * @param string $name the name attribute.
668
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
669
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
670
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
671
     * If a value is null, the corresponding attribute will not be rendered.
672
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
673
     * @return string the generated file input tag
674
     */
675 1
    public static function fileInput($name, $value = null, $options = [])
676
    {
677 1
        return static::input('file', $name, $value, $options);
678
    }
679
680
    /**
681
     * Generates a text area input.
682
     * @param string $name the input name
683
     * @param string $value the input value. Note that it will be encoded using [[encode()]].
684
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
685
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
686
     * If a value is null, the corresponding attribute will not be rendered.
687
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
688
     * The following special options are recognized:
689
     *
690
     * - `doubleEncode`: whether to double encode HTML entities in `$value`. If `false`, HTML entities in `$value` will not
691
     *   be further encoded. This option is available since version 2.0.11.
692
     *
693
     * @return string the generated text area tag
694
     */
695 8
    public static function textarea($name, $value = '', $options = [])
696
    {
697 8
        $options['name'] = $name;
698 8
        $doubleEncode = ArrayHelper::remove($options, 'doubleEncode', true);
699 8
        return static::tag('textarea', static::encode($value, $doubleEncode), $options);
700
    }
701
702
    /**
703
     * Generates a radio button input.
704
     * @param string $name the name attribute.
705
     * @param bool $checked whether the radio button should be checked.
706
     * @param array $options the tag options in terms of name-value pairs.
707
     * See [[booleanInput()]] for details about accepted attributes.
708
     *
709
     * @return string the generated radio button tag
710
     */
711 12
    public static function radio($name, $checked = false, $options = [])
712
    {
713 12
        return static::booleanInput('radio', $name, $checked, $options);
714
    }
715
716
    /**
717
     * Generates a checkbox input.
718
     * @param string $name the name attribute.
719
     * @param bool $checked whether the checkbox should be checked.
720
     * @param array $options the tag options in terms of name-value pairs.
721
     * See [[booleanInput()]] for details about accepted attributes.
722
     *
723
     * @return string the generated checkbox tag
724
     */
725 10
    public static function checkbox($name, $checked = false, $options = [])
726
    {
727 10
        return static::booleanInput('checkbox', $name, $checked, $options);
728
    }
729
730
    /**
731
     * Generates a boolean input.
732
     * @param string $type the input type. This can be either `radio` or `checkbox`.
733
     * @param string $name the name attribute.
734
     * @param bool $checked whether the checkbox should be checked.
735
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
736
     *
737
     * - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute
738
     *   is present, a hidden input will be generated so that if the checkbox is not checked and is submitted,
739
     *   the value of this attribute will still be submitted to the server via the hidden input.
740
     * - label: string, a label displayed next to the checkbox.  It will NOT be HTML-encoded. Therefore you can pass
741
     *   in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
742
     *   When this option is specified, the checkbox will be enclosed by a label tag.
743
     * - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option.
744
     *
745
     * The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will
746
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
747
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
748
     *
749
     * @return string the generated checkbox tag
750
     * @since 2.0.9
751
     */
752 22
    protected static function booleanInput($type, $name, $checked = false, $options = [])
753
    {
754
        // 'checked' option has priority over $checked argument
755 22
        if (!isset($options['checked'])) {
756 21
            $options['checked'] = (bool) $checked;
757
        }
758 22
        $value = array_key_exists('value', $options) ? $options['value'] : '1';
759 22
        if (isset($options['uncheck'])) {
760
            // add a hidden field so that if the checkbox is not selected, it still submits a value
761 6
            $hiddenOptions = [];
762 6
            if (isset($options['form'])) {
763 1
                $hiddenOptions['form'] = $options['form'];
764
            }
765
            // make sure disabled input is not sending any value
766 6
            if (!empty($options['disabled'])) {
767 2
                $hiddenOptions['disabled'] = $options['disabled'];
768
            }
769 6
            $hidden = static::hiddenInput($name, $options['uncheck'], $hiddenOptions);
770 6
            unset($options['uncheck']);
771
        } else {
772 18
            $hidden = '';
773
        }
774 22
        if (isset($options['label'])) {
775 11
            $label = $options['label'];
776 11
            $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
777 11
            unset($options['label'], $options['labelOptions']);
778 11
            $content = static::label(static::input($type, $name, $value, $options) . ' ' . $label, null, $labelOptions);
779 11
            return $hidden . $content;
780
        }
781
782 15
        return $hidden . static::input($type, $name, $value, $options);
783
    }
784
785
    /**
786
     * Generates a drop-down list.
787
     * @param string $name the input name
788
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
789
     * @param array $items the option data items. The array keys are option values, and the array values
790
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
791
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
792
     * If you have a list of data models, you may convert them into the format described above using
793
     * [[\yii\helpers\ArrayHelper::map()]].
794
     *
795
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
796
     * the labels will also be HTML-encoded.
797
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
798
     *
799
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
800
     *   to override the value and to set other tag attributes:
801
     *
802
     *   ```php
803
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
804
     *   ```
805
     *
806
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
807
     *   and the array values are the extra attributes for the corresponding option tags. For example,
808
     *
809
     *   ```php
810
     *   [
811
     *       'value1' => ['disabled' => true],
812
     *       'value2' => ['label' => 'value 2'],
813
     *   ];
814
     *   ```
815
     *
816
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
817
     *   except that the array keys represent the optgroup labels specified in $items.
818
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
819
     *   Defaults to false.
820
     * - encode: bool, whether to encode option prompt and option value characters.
821
     *   Defaults to `true`. This option is available since 2.0.3.
822
     *
823
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
824
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
825
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
826
     *
827
     * @return string the generated drop-down list tag
828
     */
829 3
    public static function dropDownList($name, $selection = null, $items = [], $options = [])
830
    {
831 3
        if (!empty($options['multiple'])) {
832 1
            return static::listBox($name, $selection, $items, $options);
833
        }
834 3
        $options['name'] = $name;
835 3
        unset($options['unselect']);
836 3
        $selectOptions = static::renderSelectOptions($selection, $items, $options);
837 3
        return static::tag('select', "\n" . $selectOptions . "\n", $options);
838
    }
839
840
    /**
841
     * Generates a list box.
842
     * @param string $name the input name
843
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
844
     * @param array $items the option data items. The array keys are option values, and the array values
845
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
846
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
847
     * If you have a list of data models, you may convert them into the format described above using
848
     * [[\yii\helpers\ArrayHelper::map()]].
849
     *
850
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
851
     * the labels will also be HTML-encoded.
852
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
853
     *
854
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
855
     *   to override the value and to set other tag attributes:
856
     *
857
     *   ```php
858
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
859
     *   ```
860
     *
861
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
862
     *   and the array values are the extra attributes for the corresponding option tags. For example,
863
     *
864
     *   ```php
865
     *   [
866
     *       'value1' => ['disabled' => true],
867
     *       'value2' => ['label' => 'value 2'],
868
     *   ];
869
     *   ```
870
     *
871
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
872
     *   except that the array keys represent the optgroup labels specified in $items.
873
     * - unselect: string, the value that will be submitted when no option is selected.
874
     *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
875
     *   mode, we can still obtain the posted unselect value.
876
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
877
     *   Defaults to false.
878
     * - encode: bool, whether to encode option prompt and option value characters.
879
     *   Defaults to `true`. This option is available since 2.0.3.
880
     *
881
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
882
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
883
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
884
     *
885
     * @return string the generated list box tag
886
     */
887 5
    public static function listBox($name, $selection = null, $items = [], $options = [])
888
    {
889 5
        if (!array_key_exists('size', $options)) {
890 5
            $options['size'] = 4;
891
        }
892 5
        if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) {
893 4
            $name .= '[]';
894
        }
895 5
        $options['name'] = $name;
896 5
        if (isset($options['unselect'])) {
897
            // add a hidden field so that if the list box has no option being selected, it still submits a value
898 4
            if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) {
899 2
                $name = substr($name, 0, -2);
900
            }
901 4
            $hiddenOptions = [];
902
            // make sure disabled input is not sending any value
903 4
            if (!empty($options['disabled'])) {
904 1
                $hiddenOptions['disabled'] = $options['disabled'];
905
            }
906 4
            $hidden = static::hiddenInput($name, $options['unselect'], $hiddenOptions);
907 4
            unset($options['unselect']);
908
        } else {
909 2
            $hidden = '';
910
        }
911 5
        $selectOptions = static::renderSelectOptions($selection, $items, $options);
912 5
        return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
913
    }
914
915
    /**
916
     * Generates a list of checkboxes.
917
     * A checkbox list allows multiple selection, like [[listBox()]].
918
     * As a result, the corresponding submitted value is an array.
919
     * @param string $name the name attribute of each checkbox.
920
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
921
     * @param array $items the data item used to generate the checkboxes.
922
     * The array keys are the checkbox values, while the array values are the corresponding labels.
923
     * @param array $options options (name => config) for the checkbox list container tag.
924
     * The following options are specially handled:
925
     *
926
     * - tag: string|false, the tag name of the container element. False to render checkbox without container.
927
     *   See also [[tag()]].
928
     * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
929
     *   By setting this option, a hidden input will be generated.
930
     * - disabled: boolean, whether the generated by unselect option hidden input should be disabled. Defaults to false.
931
     *   This option is available since version 2.0.16.
932
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
933
     *   This option is ignored if `item` option is set.
934
     * - separator: string, the HTML code that separates items.
935
     * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
936
     * - item: callable, a callback that can be used to customize the generation of the HTML code
937
     *   corresponding to a single item in $items. The signature of this callback must be:
938
     *
939
     *   ```php
940
     *   function ($index, $label, $name, $checked, $value)
941
     *   ```
942
     *
943
     *   where $index is the zero-based index of the checkbox in the whole list; $label
944
     *   is the label for the checkbox; and $name, $value and $checked represent the name,
945
     *   value and the checked status of the checkbox input, respectively.
946
     *
947
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
948
     *
949
     * @return string the generated checkbox list
950
     */
951 2
    public static function checkboxList($name, $selection = null, $items = [], $options = [])
952
    {
953 2
        if (substr($name, -2) !== '[]') {
954 2
            $name .= '[]';
955
        }
956 2
        if (ArrayHelper::isTraversable($selection)) {
957 1
            $selection = array_map('strval', (array)$selection);
958
        }
959
960 2
        $formatter = ArrayHelper::remove($options, 'item');
961 2
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
962 2
        $encode = ArrayHelper::remove($options, 'encode', true);
963 2
        $separator = ArrayHelper::remove($options, 'separator', "\n");
964 2
        $tag = ArrayHelper::remove($options, 'tag', 'div');
965
966 2
        $lines = [];
967 2
        $index = 0;
968 2
        foreach ($items as $value => $label) {
969 2
            $checked = $selection !== null &&
970 1
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
0 ignored issues
show
Bug introduced by
It seems like $selection can also be of type array; however, parameter $str2 of strcmp() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

970
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, /** @scrutinizer ignore-type */ $selection)
Loading history...
971 2
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, $selection));
0 ignored issues
show
Bug introduced by
It seems like $selection can also be of type string; however, parameter $haystack of yii\helpers\BaseArrayHelper::isIn() does only seem to accept Traversable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

971
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, /** @scrutinizer ignore-type */ $selection));
Loading history...
972 2
            if ($formatter !== null) {
973 1
                $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
974
            } else {
975 2
                $lines[] = static::checkbox($name, $checked, array_merge([
976 2
                    'value' => $value,
977 2
                    'label' => $encode ? static::encode($label) : $label,
978 2
                ], $itemOptions));
979
            }
980 2
            $index++;
981
        }
982
983 2
        if (isset($options['unselect'])) {
984
            // add a hidden field so that if the list box has no option being selected, it still submits a value
985 2
            $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
986 2
            $hiddenOptions = [];
987
            // make sure disabled input is not sending any value
988 2
            if (!empty($options['disabled'])) {
989 1
                $hiddenOptions['disabled'] = $options['disabled'];
990
            }
991 2
            $hidden = static::hiddenInput($name2, $options['unselect'], $hiddenOptions);
992 2
            unset($options['unselect'], $options['disabled']);
993
        } else {
994 1
            $hidden = '';
995
        }
996
997 2
        $visibleContent = implode($separator, $lines);
0 ignored issues
show
Bug introduced by
It seems like $separator can also be of type null; however, parameter $glue of implode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

997
        $visibleContent = implode(/** @scrutinizer ignore-type */ $separator, $lines);
Loading history...
998
999 2
        if ($tag === false) {
1000 1
            return $hidden . $visibleContent;
1001
        }
1002
1003 2
        return $hidden . static::tag($tag, $visibleContent, $options);
1004
    }
1005
1006
    /**
1007
     * Generates a list of radio buttons.
1008
     * A radio button list is like a checkbox list, except that it only allows single selection.
1009
     * @param string $name the name attribute of each radio button.
1010
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
1011
     * @param array $items the data item used to generate the radio buttons.
1012
     * The array keys are the radio button values, while the array values are the corresponding labels.
1013
     * @param array $options options (name => config) for the radio button list container tag.
1014
     * The following options are specially handled:
1015
     *
1016
     * - tag: string|false, the tag name of the container element. False to render radio buttons without container.
1017
     *   See also [[tag()]].
1018
     * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
1019
     *   By setting this option, a hidden input will be generated.
1020
     * - disabled: boolean, whether the generated by unselect option hidden input should be disabled. Defaults to false.
1021
     *   This option is available since version 2.0.16.
1022
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1023
     *   This option is ignored if `item` option is set.
1024
     * - separator: string, the HTML code that separates items.
1025
     * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
1026
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1027
     *   corresponding to a single item in $items. The signature of this callback must be:
1028
     *
1029
     *   ```php
1030
     *   function ($index, $label, $name, $checked, $value)
1031
     *   ```
1032
     *
1033
     *   where $index is the zero-based index of the radio button in the whole list; $label
1034
     *   is the label for the radio button; and $name, $value and $checked represent the name,
1035
     *   value and the checked status of the radio button input, respectively.
1036
     *
1037
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1038
     *
1039
     * @return string the generated radio button list
1040
     */
1041 3
    public static function radioList($name, $selection = null, $items = [], $options = [])
1042
    {
1043 3
        if (ArrayHelper::isTraversable($selection)) {
1044 1
            $selection = array_map('strval', (array)$selection);
1045
        }
1046
1047 3
        $formatter = ArrayHelper::remove($options, 'item');
1048 3
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
1049 3
        $encode = ArrayHelper::remove($options, 'encode', true);
1050 3
        $separator = ArrayHelper::remove($options, 'separator', "\n");
1051 3
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1052
1053 3
        $hidden = '';
1054 3
        if (isset($options['unselect'])) {
1055
            // add a hidden field so that if the list box has no option being selected, it still submits a value
1056 3
            $hiddenOptions = [];
1057
            // make sure disabled input is not sending any value
1058 3
            if (!empty($options['disabled'])) {
1059 1
                $hiddenOptions['disabled'] = $options['disabled'];
1060
            }
1061 3
            $hidden =  static::hiddenInput($name, $options['unselect'], $hiddenOptions);
1062 3
            unset($options['unselect'], $options['disabled']);
1063
        }
1064
1065 3
        $lines = [];
1066 3
        $index = 0;
1067 3
        foreach ($items as $value => $label) {
1068 3
            $checked = $selection !== null &&
1069 1
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
0 ignored issues
show
Bug introduced by
It seems like $selection can also be of type array; however, parameter $str2 of strcmp() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1069
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, /** @scrutinizer ignore-type */ $selection)
Loading history...
1070 3
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, $selection));
0 ignored issues
show
Bug introduced by
It seems like $selection can also be of type string; however, parameter $haystack of yii\helpers\BaseArrayHelper::isIn() does only seem to accept Traversable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1070
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, /** @scrutinizer ignore-type */ $selection));
Loading history...
1071 3
            if ($formatter !== null) {
1072 1
                $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
1073
            } else {
1074 3
                $lines[] = static::radio($name, $checked, array_merge([
1075 3
                    'value' => $value,
1076 3
                    'label' => $encode ? static::encode($label) : $label,
1077 3
                ], $itemOptions));
1078
            }
1079 3
            $index++;
1080
        }
1081 3
        $visibleContent = implode($separator, $lines);
0 ignored issues
show
Bug introduced by
It seems like $separator can also be of type null; however, parameter $glue of implode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1081
        $visibleContent = implode(/** @scrutinizer ignore-type */ $separator, $lines);
Loading history...
1082
1083 3
        if ($tag === false) {
1084 1
            return $hidden . $visibleContent;
1085
        }
1086
1087 3
        return $hidden . static::tag($tag, $visibleContent, $options);
1088
    }
1089
1090
    /**
1091
     * Generates an unordered list.
1092
     * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
1093
     * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
1094
     * @param array $options options (name => config) for the radio button list. The following options are supported:
1095
     *
1096
     * - encode: boolean, whether to HTML-encode the items. Defaults to true.
1097
     *   This option is ignored if the `item` option is specified.
1098
     * - separator: string, the HTML code that separates items. Defaults to a simple newline (`"\n"`).
1099
     *   This option is available since version 2.0.7.
1100
     * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
1101
     * - item: callable, a callback that is used to generate each individual list item.
1102
     *   The signature of this callback must be:
1103
     *
1104
     *   ```php
1105
     *   function ($item, $index)
1106
     *   ```
1107
     *
1108
     *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
1109
     *   the whole list item tag.
1110
     *
1111
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1112
     *
1113
     * @return string the generated unordered list. An empty list tag will be returned if `$items` is empty.
1114
     */
1115 4
    public static function ul($items, $options = [])
1116
    {
1117 4
        $tag = ArrayHelper::remove($options, 'tag', 'ul');
1118 4
        $encode = ArrayHelper::remove($options, 'encode', true);
1119 4
        $formatter = ArrayHelper::remove($options, 'item');
1120 4
        $separator = ArrayHelper::remove($options, 'separator', "\n");
1121 4
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
1122
1123 4
        if (empty($items)) {
1124 2
            return static::tag($tag, '', $options);
1125
        }
1126
1127 4
        $results = [];
1128 4
        foreach ($items as $index => $item) {
1129 4
            if ($formatter !== null) {
1130 2
                $results[] = call_user_func($formatter, $item, $index);
1131
            } else {
1132 4
                $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
1133
            }
1134
        }
1135
1136 4
        return static::tag(
1137 4
            $tag,
1138 4
            $separator . implode($separator, $results) . $separator,
0 ignored issues
show
Bug introduced by
It seems like $separator can also be of type null; however, parameter $glue of implode() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1138
            $separator . implode(/** @scrutinizer ignore-type */ $separator, $results) . $separator,
Loading history...
1139 4
            $options
1140
        );
1141
    }
1142
1143
    /**
1144
     * Generates an ordered list.
1145
     * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
1146
     * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
1147
     * @param array $options options (name => config) for the radio button list. The following options are supported:
1148
     *
1149
     * - encode: boolean, whether to HTML-encode the items. Defaults to true.
1150
     *   This option is ignored if the `item` option is specified.
1151
     * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
1152
     * - item: callable, a callback that is used to generate each individual list item.
1153
     *   The signature of this callback must be:
1154
     *
1155
     *   ```php
1156
     *   function ($item, $index)
1157
     *   ```
1158
     *
1159
     *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
1160
     *   the whole list item tag.
1161
     *
1162
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1163
     *
1164
     * @return string the generated ordered list. An empty string is returned if `$items` is empty.
1165
     */
1166 1
    public static function ol($items, $options = [])
1167
    {
1168 1
        $options['tag'] = 'ol';
1169 1
        return static::ul($items, $options);
1170
    }
1171
1172
    /**
1173
     * Generates a label tag for the given model attribute.
1174
     * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
1175
     * @param Model $model the model object
1176
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1177
     * about attribute expression.
1178
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1179
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1180
     * If a value is null, the corresponding attribute will not be rendered.
1181
     * The following options are specially handled:
1182
     *
1183
     * - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
1184
     *   If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
1185
     *   (after encoding).
1186
     *
1187
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1188
     *
1189
     * @return string the generated label tag
1190
     */
1191 14
    public static function activeLabel($model, $attribute, $options = [])
1192
    {
1193 14
        $for = ArrayHelper::remove($options, 'for', static::getInputId($model, $attribute));
1194 14
        $attribute = static::getAttributeName($attribute);
1195 14
        $label = ArrayHelper::remove($options, 'label', static::encode($model->getAttributeLabel($attribute)));
1196 14
        return static::label($label, $for, $options);
1197
    }
1198
1199
    /**
1200
     * Generates a hint tag for the given model attribute.
1201
     * The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]].
1202
     * If no hint content can be obtained, method will return an empty string.
1203
     * @param Model $model the model object
1204
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1205
     * about attribute expression.
1206
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1207
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1208
     * If a value is null, the corresponding attribute will not be rendered.
1209
     * The following options are specially handled:
1210
     *
1211
     * - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]].
1212
     *   If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display
1213
     *   (without encoding).
1214
     *
1215
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1216
     *
1217
     * @return string the generated hint tag
1218
     * @since 2.0.4
1219
     */
1220 14
    public static function activeHint($model, $attribute, $options = [])
1221
    {
1222 14
        $attribute = static::getAttributeName($attribute);
1223 14
        $hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute);
1224 14
        if (empty($hint)) {
1225 4
            return '';
1226
        }
1227 10
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1228 10
        unset($options['hint']);
1229 10
        return static::tag($tag, $hint, $options);
1230
    }
1231
1232
    /**
1233
     * Generates a summary of the validation errors.
1234
     * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
1235
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
1236
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1237
     *
1238
     * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
1239
     * - footer: string, the footer HTML for the error summary. Defaults to empty string.
1240
     * - encode: boolean, if set to false then the error messages won't be encoded. Defaults to `true`.
1241
     * - showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise
1242
     *   only the first error message for each attribute will be shown. Defaults to `false`.
1243
     *   Option is available since 2.0.10.
1244
     *
1245
     * The rest of the options will be rendered as the attributes of the container tag.
1246
     *
1247
     * @return string the generated error summary
1248
     */
1249 8
    public static function errorSummary($models, $options = [])
1250
    {
1251 8
        $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
1252 8
        $footer = ArrayHelper::remove($options, 'footer', '');
1253 8
        $encode = ArrayHelper::remove($options, 'encode', true);
1254 8
        $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
1255 8
        unset($options['header']);
1256 8
        $lines = self::collectErrors($models, $encode, $showAllErrors);
1257 8
        if (empty($lines)) {
1258
            // still render the placeholder for client-side validation use
1259 2
            $content = '<ul></ul>';
1260 2
            $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
1261
        } else {
1262 6
            $content = '<ul><li>' . implode("</li>\n<li>", $lines) . '</li></ul>';
1263
        }
1264
1265 8
        return Html::tag('div', $header . $content . $footer, $options);
1266
    }
1267
1268
    /**
1269
     * Return array of the validation errors
1270
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
1271
     * @param $encode boolean, if set to false then the error messages won't be encoded.
1272
     * @param $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
1273
     * only the first error message for each attribute will be shown.
1274
     * @return array of the validation errors
1275
     * @since 2.0.14
1276
     */
1277 8
    private static function collectErrors($models, $encode, $showAllErrors)
1278
    {
1279 8
        $lines = [];
1280 8
        if (!is_array($models)) {
1281 8
            $models = [$models];
1282
        }
1283
1284 8
        foreach ($models as $model) {
1285 8
            $lines = array_unique(array_merge($lines, $model->getErrorSummary($showAllErrors)));
1286
        }
1287
1288
        // If there are the same error messages for different attributes, array_unique will leave gaps
1289
        // between sequential keys. Applying array_values to reorder array keys.
1290 8
        $lines = array_values($lines);
1291
1292 8
        if ($encode) {
1293 7
            foreach ($lines as &$line) {
1294 5
                $line = Html::encode($line);
1295
            }
1296
        }
1297
1298 8
        return $lines;
1299
    }
1300
1301
    /**
1302
     * Generates a tag that contains the first validation error of the specified model attribute.
1303
     * Note that even if there is no validation error, this method will still return an empty error tag.
1304
     * @param Model $model the model object
1305
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1306
     * about attribute expression.
1307
     * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
1308
     * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1309
     *
1310
     * The following options are specially handled:
1311
     *
1312
     * - tag: this specifies the tag name. If not set, "div" will be used.
1313
     *   See also [[tag()]].
1314
     * - encode: boolean, if set to false then the error message won't be encoded.
1315
     * - errorSource (since 2.0.14): \Closure|callable, callback that will be called to obtain an error message.
1316
     *   The signature of the callback must be: `function ($model, $attribute)` and return a string.
1317
     *   When not set, the `$model->getFirstError()` method will be called.
1318
     *
1319
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1320
     *
1321
     * @return string the generated label tag
1322
     */
1323 13
    public static function error($model, $attribute, $options = [])
1324
    {
1325 13
        $attribute = static::getAttributeName($attribute);
1326 13
        $errorSource = ArrayHelper::remove($options, 'errorSource');
1327 13
        if ($errorSource !== null) {
1328 1
            $error = call_user_func($errorSource, $model, $attribute);
1329
        } else {
1330 13
            $error = $model->getFirstError($attribute);
1331
        }
1332 13
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1333 13
        $encode = ArrayHelper::remove($options, 'encode', true);
1334 13
        return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
1335
    }
1336
1337
    /**
1338
     * Generates an input tag for the given model attribute.
1339
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1340
     * unless they are explicitly specified in `$options`.
1341
     * @param string $type the input type (e.g. 'text', 'password')
1342
     * @param Model $model the model object
1343
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1344
     * about attribute expression.
1345
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1346
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1347
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1348
     * @return string the generated input tag
1349
     */
1350 30
    public static function activeInput($type, $model, $attribute, $options = [])
1351
    {
1352 30
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1353 30
        $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1354 30
        if (!array_key_exists('id', $options)) {
1355 28
            $options['id'] = static::getInputId($model, $attribute);
1356
        }
1357
1358 30
        static::setActivePlaceholder($model, $attribute, $options);
1359 30
        self::normalizeMaxLength($model, $attribute, $options);
1360
1361 30
        return static::input($type, $name, $value, $options);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type array; however, parameter $value of yii\helpers\BaseHtml::input() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1361
        return static::input($type, $name, /** @scrutinizer ignore-type */ $value, $options);
Loading history...
1362
    }
1363
1364
    /**
1365
     * If `maxlength` option is set true and the model attribute is validated by a string validator,
1366
     * the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1367
     * @param Model $model the model object
1368
     * @param string $attribute the attribute name or expression.
1369
     * @param array $options the tag options in terms of name-value pairs.
1370
     */
1371 34
    private static function normalizeMaxLength($model, $attribute, &$options)
1372
    {
1373 34
        if (isset($options['maxlength']) && $options['maxlength'] === true) {
1374 4
            unset($options['maxlength']);
1375 4
            $attrName = static::getAttributeName($attribute);
1376 4
            foreach ($model->getActiveValidators($attrName) as $validator) {
1377 4
                if ($validator instanceof StringValidator && $validator->max !== null) {
1378 4
                    $options['maxlength'] = $validator->max;
1379 4
                    break;
1380
                }
1381
            }
1382
        }
1383 34
    }
1384
1385
    /**
1386
     * Generates a text input tag for the given model attribute.
1387
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1388
     * unless they are explicitly specified in `$options`.
1389
     * @param Model $model the model object
1390
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1391
     * about attribute expression.
1392
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1393
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1394
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1395
     * The following special options are recognized:
1396
     *
1397
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1398
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1399
     *   This is available since version 2.0.3.
1400
     * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
1401
     *   as a placeholder (this behavior is available since version 2.0.14).
1402
     *
1403
     * @return string the generated input tag
1404
     */
1405 17
    public static function activeTextInput($model, $attribute, $options = [])
1406
    {
1407 17
        return static::activeInput('text', $model, $attribute, $options);
1408
    }
1409
1410
    /**
1411
     * Generate placeholder from model attribute label.
1412
     *
1413
     * @param Model $model the model object
1414
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1415
     * about attribute expression.
1416
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1417
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1418
     * @since 2.0.14
1419
     */
1420 33
    protected static function setActivePlaceholder($model, $attribute, &$options = [])
1421
    {
1422 33
        if (isset($options['placeholder']) && $options['placeholder'] === true) {
1423 2
            $attribute = static::getAttributeName($attribute);
1424 2
            $options['placeholder'] = $model->getAttributeLabel($attribute);
1425
        }
1426 33
    }
1427
1428
    /**
1429
     * Generates a hidden input tag for the given model attribute.
1430
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1431
     * unless they are explicitly specified in `$options`.
1432
     * @param Model $model the model object
1433
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1434
     * about attribute expression.
1435
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1436
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1437
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1438
     * @return string the generated input tag
1439
     */
1440 5
    public static function activeHiddenInput($model, $attribute, $options = [])
1441
    {
1442 5
        return static::activeInput('hidden', $model, $attribute, $options);
1443
    }
1444
1445
    /**
1446
     * Generates a password input tag for the given model attribute.
1447
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1448
     * unless they are explicitly specified in `$options`.
1449
     * @param Model $model the model object
1450
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1451
     * about attribute expression.
1452
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1453
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1454
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1455
     * The following special options are recognized:
1456
     *
1457
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1458
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1459
     *   This option is available since version 2.0.6.
1460
     * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
1461
     *   as a placeholder (this behavior is available since version 2.0.14).
1462
     *
1463
     * @return string the generated input tag
1464
     */
1465 3
    public static function activePasswordInput($model, $attribute, $options = [])
1466
    {
1467 3
        return static::activeInput('password', $model, $attribute, $options);
1468
    }
1469
1470
    /**
1471
     * Generates a file input tag for the given model attribute.
1472
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1473
     * unless they are explicitly specified in `$options`.
1474
     * Additionally, if a separate set of HTML options array is defined inside `$options` with a key named `hiddenOptions`,
1475
     * it will be passed to the `activeHiddenInput` field as its own `$options` parameter.
1476
     * @param Model $model the model object
1477
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1478
     * about attribute expression.
1479
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1480
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1481
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1482
     * If `hiddenOptions` parameter which is another set of HTML options array is defined, it will be extracted
1483
     * from `$options` to be used for the hidden input.
1484
     * @return string the generated input tag
1485
     */
1486 2
    public static function activeFileInput($model, $attribute, $options = [])
1487
    {
1488 2
        $hiddenOptions = ['id' => null, 'value' => ''];
1489 2
        if (isset($options['name'])) {
1490 1
            $hiddenOptions['name'] = $options['name'];
1491
        }
1492
        // make sure disabled input is not sending any value
1493 2
        if (!empty($options['disabled'])) {
1494 1
            $hiddenOptions['disabled'] = $options['disabled'];
1495
        }
1496 2
        $hiddenOptions = ArrayHelper::merge($hiddenOptions, ArrayHelper::remove($options, 'hiddenOptions', []));
1497
        // Add a hidden field so that if a model only has a file field, we can
1498
        // still use isset($_POST[$modelClass]) to detect if the input is submitted.
1499
        // The hidden input will be assigned its own set of html options via `$hiddenOptions`.
1500
        // This provides the possibility to interact with the hidden field via client script.
1501
        // Note: For file-field-only model with `disabled` option set to `true` input submitting detection won't work.
1502
1503 2
        return static::activeHiddenInput($model, $attribute, $hiddenOptions)
1504 2
            . static::activeInput('file', $model, $attribute, $options);
1505
    }
1506
1507
    /**
1508
     * Generates a textarea tag for the given model attribute.
1509
     * The model attribute value will be used as the content in the textarea.
1510
     * @param Model $model the model object
1511
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1512
     * about attribute expression.
1513
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1514
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1515
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1516
     * The following special options are recognized:
1517
     *
1518
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1519
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1520
     *   This option is available since version 2.0.6.
1521
     * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
1522
     *   as a placeholder (this behavior is available since version 2.0.14).
1523
     *
1524
     * @return string the generated textarea tag
1525
     */
1526 4
    public static function activeTextarea($model, $attribute, $options = [])
1527
    {
1528 4
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1529 4
        if (isset($options['value'])) {
1530 1
            $value = $options['value'];
1531 1
            unset($options['value']);
1532
        } else {
1533 3
            $value = static::getAttributeValue($model, $attribute);
1534
        }
1535 4
        if (!array_key_exists('id', $options)) {
1536 4
            $options['id'] = static::getInputId($model, $attribute);
1537
        }
1538 4
        self::normalizeMaxLength($model, $attribute, $options);
1539 4
        static::setActivePlaceholder($model, $attribute, $options);
1540 4
        return static::textarea($name, $value, $options);
1541
    }
1542
1543
    /**
1544
     * Generates a radio button tag together with a label for the given model attribute.
1545
     * This method will generate the "checked" tag attribute according to the model attribute value.
1546
     * @param Model $model the model object
1547
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1548
     * about attribute expression.
1549
     * @param array $options the tag options in terms of name-value pairs.
1550
     * See [[booleanInput()]] for details about accepted attributes.
1551
     *
1552
     * @return string the generated radio button tag
1553
     */
1554 4
    public static function activeRadio($model, $attribute, $options = [])
1555
    {
1556 4
        return static::activeBooleanInput('radio', $model, $attribute, $options);
1557
    }
1558
1559
    /**
1560
     * Generates a checkbox tag together with a label for the given model attribute.
1561
     * This method will generate the "checked" tag attribute according to the model attribute value.
1562
     * @param Model $model the model object
1563
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1564
     * about attribute expression.
1565
     * @param array $options the tag options in terms of name-value pairs.
1566
     * See [[booleanInput()]] for details about accepted attributes.
1567
     *
1568
     * @return string the generated checkbox tag
1569
     */
1570 4
    public static function activeCheckbox($model, $attribute, $options = [])
1571
    {
1572 4
        return static::activeBooleanInput('checkbox', $model, $attribute, $options);
1573
    }
1574
1575
    /**
1576
     * Generates a boolean input
1577
     * This method is mainly called by [[activeCheckbox()]] and [[activeRadio()]].
1578
     * @param string $type the input type. This can be either `radio` or `checkbox`.
1579
     * @param Model $model the model object
1580
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1581
     * about attribute expression.
1582
     * @param array $options the tag options in terms of name-value pairs.
1583
     * See [[booleanInput()]] for details about accepted attributes.
1584
     * @return string the generated input element
1585
     * @since 2.0.9
1586
     */
1587 8
    protected static function activeBooleanInput($type, $model, $attribute, $options = [])
1588
    {
1589 8
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1590 8
        $value = static::getAttributeValue($model, $attribute);
1591
1592 8
        if (!array_key_exists('value', $options)) {
1593 8
            $options['value'] = '1';
1594
        }
1595 8
        if (!array_key_exists('uncheck', $options)) {
1596 4
            $options['uncheck'] = '0';
1597 4
        } elseif ($options['uncheck'] === false) {
1598 4
            unset($options['uncheck']);
1599
        }
1600 8
        if (!array_key_exists('label', $options)) {
1601 4
            $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
1602 4
        } elseif ($options['label'] === false) {
1603 4
            unset($options['label']);
1604
        }
1605
1606 8
        $checked = "$value" === "{$options['value']}";
1607
1608 8
        if (!array_key_exists('id', $options)) {
1609 8
            $options['id'] = static::getInputId($model, $attribute);
1610
        }
1611
1612 8
        return static::$type($name, $checked, $options);
1613
    }
1614
1615
    /**
1616
     * Generates a drop-down list for the given model attribute.
1617
     * The selection of the drop-down list is taken from the value of the model attribute.
1618
     * @param Model $model the model object
1619
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1620
     * about attribute expression.
1621
     * @param array $items the option data items. The array keys are option values, and the array values
1622
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1623
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1624
     * If you have a list of data models, you may convert them into the format described above using
1625
     * [[\yii\helpers\ArrayHelper::map()]].
1626
     *
1627
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1628
     * the labels will also be HTML-encoded.
1629
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1630
     *
1631
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1632
     *   to override the value and to set other tag attributes:
1633
     *
1634
     *   ```php
1635
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1636
     *   ```
1637
     *
1638
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1639
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1640
     *
1641
     *   ```php
1642
     *   [
1643
     *       'value1' => ['disabled' => true],
1644
     *       'value2' => ['label' => 'value 2'],
1645
     *   ];
1646
     *   ```
1647
     *
1648
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1649
     *   except that the array keys represent the optgroup labels specified in $items.
1650
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1651
     *   Defaults to false.
1652
     * - encode: bool, whether to encode option prompt and option value characters.
1653
     *   Defaults to `true`. This option is available since 2.0.3.
1654
     *
1655
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1656
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1657
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1658
     *
1659
     * @return string the generated drop-down list tag
1660
     */
1661 3
    public static function activeDropDownList($model, $attribute, $items, $options = [])
1662
    {
1663 3
        if (empty($options['multiple'])) {
1664 2
            return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
1665
        }
1666
1667 1
        return static::activeListBox($model, $attribute, $items, $options);
1668
    }
1669
1670
    /**
1671
     * Generates a list box.
1672
     * The selection of the list box is taken from the value of the model attribute.
1673
     * @param Model $model the model object
1674
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1675
     * about attribute expression.
1676
     * @param array $items the option data items. The array keys are option values, and the array values
1677
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1678
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1679
     * If you have a list of data models, you may convert them into the format described above using
1680
     * [[\yii\helpers\ArrayHelper::map()]].
1681
     *
1682
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1683
     * the labels will also be HTML-encoded.
1684
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1685
     *
1686
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1687
     *   to override the value and to set other tag attributes:
1688
     *
1689
     *   ```php
1690
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1691
     *   ```
1692
     *
1693
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1694
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1695
     *
1696
     *   ```php
1697
     *   [
1698
     *       'value1' => ['disabled' => true],
1699
     *       'value2' => ['label' => 'value 2'],
1700
     *   ];
1701
     *   ```
1702
     *
1703
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1704
     *   except that the array keys represent the optgroup labels specified in $items.
1705
     * - unselect: string, the value that will be submitted when no option is selected.
1706
     *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
1707
     *   mode, we can still obtain the posted unselect value.
1708
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1709
     *   Defaults to false.
1710
     * - encode: bool, whether to encode option prompt and option value characters.
1711
     *   Defaults to `true`. This option is available since 2.0.3.
1712
     *
1713
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1714
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1715
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1716
     *
1717
     * @return string the generated list box tag
1718
     */
1719 3
    public static function activeListBox($model, $attribute, $items, $options = [])
1720
    {
1721 3
        return static::activeListInput('listBox', $model, $attribute, $items, $options);
1722
    }
1723
1724
    /**
1725
     * Generates a list of checkboxes.
1726
     * A checkbox list allows multiple selection, like [[listBox()]].
1727
     * As a result, the corresponding submitted value is an array.
1728
     * The selection of the checkbox list is taken from the value of the model attribute.
1729
     * @param Model $model the model object
1730
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1731
     * about attribute expression.
1732
     * @param array $items the data item used to generate the checkboxes.
1733
     * The array keys are the checkbox values, and the array values are the corresponding labels.
1734
     * Note that the labels will NOT be HTML-encoded, while the values will.
1735
     * @param array $options options (name => config) for the checkbox list container tag.
1736
     * The following options are specially handled:
1737
     *
1738
     * - tag: string|false, the tag name of the container element. False to render checkbox without container.
1739
     *   See also [[tag()]].
1740
     * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
1741
     *   You may set this option to be null to prevent default value submission.
1742
     *   If this option is not set, an empty string will be submitted.
1743
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1744
     *   This option is ignored if `item` option is set.
1745
     * - separator: string, the HTML code that separates items.
1746
     * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
1747
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1748
     *   corresponding to a single item in $items. The signature of this callback must be:
1749
     *
1750
     *   ```php
1751
     *   function ($index, $label, $name, $checked, $value)
1752
     *   ```
1753
     *
1754
     *   where $index is the zero-based index of the checkbox in the whole list; $label
1755
     *   is the label for the checkbox; and $name, $value and $checked represent the name,
1756
     *   value and the checked status of the checkbox input.
1757
     *
1758
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1759
     *
1760
     * @return string the generated checkbox list
1761
     */
1762 1
    public static function activeCheckboxList($model, $attribute, $items, $options = [])
1763
    {
1764 1
        return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
1765
    }
1766
1767
    /**
1768
     * Generates a list of radio buttons.
1769
     * A radio button list is like a checkbox list, except that it only allows single selection.
1770
     * The selection of the radio buttons is taken from the value of the model attribute.
1771
     * @param Model $model the model object
1772
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1773
     * about attribute expression.
1774
     * @param array $items the data item used to generate the radio buttons.
1775
     * The array keys are the radio values, and the array values are the corresponding labels.
1776
     * Note that the labels will NOT be HTML-encoded, while the values will.
1777
     * @param array $options options (name => config) for the radio button list container tag.
1778
     * The following options are specially handled:
1779
     *
1780
     * - tag: string|false, the tag name of the container element. False to render radio button without container.
1781
     *   See also [[tag()]].
1782
     * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
1783
     *   You may set this option to be null to prevent default value submission.
1784
     *   If this option is not set, an empty string will be submitted.
1785
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1786
     *   This option is ignored if `item` option is set.
1787
     * - separator: string, the HTML code that separates items.
1788
     * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
1789
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1790
     *   corresponding to a single item in $items. The signature of this callback must be:
1791
     *
1792
     *   ```php
1793
     *   function ($index, $label, $name, $checked, $value)
1794
     *   ```
1795
     *
1796
     *   where $index is the zero-based index of the radio button in the whole list; $label
1797
     *   is the label for the radio button; and $name, $value and $checked represent the name,
1798
     *   value and the checked status of the radio button input.
1799
     *
1800
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1801
     *
1802
     * @return string the generated radio button list
1803
     */
1804 2
    public static function activeRadioList($model, $attribute, $items, $options = [])
1805
    {
1806 2
        return static::activeListInput('radioList', $model, $attribute, $items, $options);
1807
    }
1808
1809
    /**
1810
     * Generates a list of input fields.
1811
     * This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckboxList()]].
1812
     * @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'.
1813
     * @param Model $model the model object
1814
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1815
     * about attribute expression.
1816
     * @param array $items the data item used to generate the input fields.
1817
     * The array keys are the input values, and the array values are the corresponding labels.
1818
     * Note that the labels will NOT be HTML-encoded, while the values will.
1819
     * @param array $options options (name => config) for the input list. The supported special options
1820
     * depend on the input type specified by `$type`.
1821
     * @return string the generated input list
1822
     */
1823 8
    protected static function activeListInput($type, $model, $attribute, $items, $options = [])
1824
    {
1825 8
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1826 8
        $selection = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1827 8
        if (!array_key_exists('unselect', $options)) {
1828 8
            $options['unselect'] = '';
1829
        }
1830 8
        if (!array_key_exists('id', $options)) {
1831 6
            $options['id'] = static::getInputId($model, $attribute);
1832
        }
1833
1834 8
        return static::$type($name, $selection, $items, $options);
1835
    }
1836
1837
    /**
1838
     * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
1839
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
1840
     * @param array $items the option data items. The array keys are option values, and the array values
1841
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1842
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1843
     * If you have a list of data models, you may convert them into the format described above using
1844
     * [[\yii\helpers\ArrayHelper::map()]].
1845
     *
1846
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1847
     * the labels will also be HTML-encoded.
1848
     * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
1849
     * This method will take out these elements, if any: "prompt", "options" and "groups". See more details
1850
     * in [[dropDownList()]] for the explanation of these elements.
1851
     *
1852
     * @return string the generated list options
1853
     */
1854 8
    public static function renderSelectOptions($selection, $items, &$tagOptions = [])
1855
    {
1856 8
        if (ArrayHelper::isTraversable($selection)) {
1857 3
            $selection = array_map('strval', (array)$selection);
1858
        }
1859
1860 8
        $lines = [];
1861 8
        $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
1862 8
        $encode = ArrayHelper::remove($tagOptions, 'encode', true);
1863 8
        if (isset($tagOptions['prompt'])) {
1864 3
            $promptOptions = ['value' => ''];
1865 3
            if (is_string($tagOptions['prompt'])) {
1866 3
                $promptText = $tagOptions['prompt'];
1867
            } else {
1868 1
                $promptText = $tagOptions['prompt']['text'];
1869 1
                $promptOptions = array_merge($promptOptions, $tagOptions['prompt']['options']);
1870
            }
1871 3
            $promptText = $encode ? static::encode($promptText) : $promptText;
1872 3
            if ($encodeSpaces) {
1873 1
                $promptText = str_replace(' ', '&nbsp;', $promptText);
1874
            }
1875 3
            $lines[] = static::tag('option', $promptText, $promptOptions);
1876
        }
1877
1878 8
        $options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
1879 8
        $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
1880 8
        unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
1881 8
        $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
1882 8
        $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
1883
1884 8
        foreach ($items as $key => $value) {
1885 7
            if (is_array($value)) {
1886 1
                $groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
1887 1
                if (!isset($groupAttrs['label'])) {
1888 1
                    $groupAttrs['label'] = $key;
1889
                }
1890 1
                $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
1891 1
                $content = static::renderSelectOptions($selection, $value, $attrs);
1892 1
                $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
1893
            } else {
1894 7
                $attrs = isset($options[$key]) ? $options[$key] : [];
1895 7
                $attrs['value'] = (string) $key;
1896 7
                if (!array_key_exists('selected', $attrs)) {
1897 7
                    $attrs['selected'] = $selection !== null &&
1898 5
                        (!ArrayHelper::isTraversable($selection) && !strcmp($key, $selection)
0 ignored issues
show
Bug introduced by
It seems like $selection can also be of type array; however, parameter $str2 of strcmp() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1898
                        (!ArrayHelper::isTraversable($selection) && !strcmp($key, /** @scrutinizer ignore-type */ $selection)
Loading history...
1899 5
                        || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$key, $selection));
0 ignored issues
show
Bug introduced by
It seems like $selection can also be of type string; however, parameter $haystack of yii\helpers\BaseArrayHelper::isIn() does only seem to accept Traversable|array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

1899
                        || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$key, /** @scrutinizer ignore-type */ $selection));
Loading history...
1900
                }
1901 7
                $text = $encode ? static::encode($value) : $value;
1902 7
                if ($encodeSpaces) {
1903 2
                    $text = str_replace(' ', '&nbsp;', $text);
1904
                }
1905 7
                $lines[] = static::tag('option', $text, $attrs);
1906
            }
1907
        }
1908
1909 8
        return implode("\n", $lines);
1910
    }
1911
1912
    /**
1913
     * Renders the HTML tag attributes.
1914
     *
1915
     * Attributes whose values are of boolean type will be treated as
1916
     * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
1917
     *
1918
     * Attributes whose values are null will not be rendered.
1919
     *
1920
     * The values of attributes will be HTML-encoded using [[encode()]].
1921
     *
1922
     * The "data" attribute is specially handled when it is receiving an array value. In this case,
1923
     * the array will be "expanded" and a list data attributes will be rendered. For example,
1924
     * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered:
1925
     * `data-id="1" data-name="yii"`.
1926
     * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as:
1927
     * `data-params='{"id":1,"name":"yii"}' data-status="ok"`.
1928
     *
1929
     * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
1930
     * @return string the rendering result. If the attributes are not empty, they will be rendered
1931
     * into a string with a leading white space (so that it can be directly appended to the tag name
1932
     * in a tag. If there is no attribute, an empty string will be returned.
1933
     * @see addCssClass()
1934
     */
1935 225
    public static function renderTagAttributes($attributes)
1936
    {
1937 225
        if (count($attributes) > 1) {
1938 170
            $sorted = [];
1939 170
            foreach (static::$attributeOrder as $name) {
1940 170
                if (isset($attributes[$name])) {
1941 170
                    $sorted[$name] = $attributes[$name];
1942
                }
1943
            }
1944 170
            $attributes = array_merge($sorted, $attributes);
1945
        }
1946
1947 225
        $html = '';
1948 225
        foreach ($attributes as $name => $value) {
1949 214
            if (is_bool($value)) {
1950 37
                if ($value) {
1951 37
                    $html .= " $name";
1952
                }
1953 214
            } elseif (is_array($value)) {
1954 10
                if (in_array($name, static::$dataAttributes)) {
1955 3
                    foreach ($value as $n => $v) {
1956 3
                        if (is_array($v)) {
1957 1
                            $html .= " $name-$n='" . Json::htmlEncode($v) . "'";
1958 3
                        } elseif (is_bool($v)) {
1959 1
                            if ($v) {
1960 1
                                $html .= " $name-$n";
1961
                            }
1962
                        } else {
1963 3
                            $html .= " $name-$n=\"" . static::encode($v) . '"';
1964
                        }
1965
                    }
1966 9
                } elseif ($name === 'class') {
1967 8
                    if (empty($value)) {
1968 8
                        continue;
1969
                    }
1970 3
                    $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
1971 2
                } elseif ($name === 'style') {
1972 1
                    if (empty($value)) {
1973 1
                        continue;
1974
                    }
1975 1
                    $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
1976
                } else {
1977 5
                    $html .= " $name='" . Json::htmlEncode($value) . "'";
1978
                }
1979 208
            } elseif ($value !== null) {
1980 210
                $html .= " $name=\"" . static::encode($value) . '"';
1981
            }
1982
        }
1983
1984 225
        return $html;
1985
    }
1986
1987
    /**
1988
     * Adds a CSS class (or several classes) to the specified options.
1989
     *
1990
     * If the CSS class is already in the options, it will not be added again.
1991
     * If class specification at given options is an array, and some class placed there with the named (string) key,
1992
     * overriding of such key will have no effect. For example:
1993
     *
1994
     * ```php
1995
     * $options = ['class' => ['persistent' => 'initial']];
1996
     * Html::addCssClass($options, ['persistent' => 'override']);
1997
     * var_dump($options['class']); // outputs: array('persistent' => 'initial');
1998
     * ```
1999
     *
2000
     * @param array $options the options to be modified.
2001
     * @param string|array $class the CSS class(es) to be added
2002
     * @see mergeCssClasses()
2003
     * @see removeCssClass()
2004
     */
2005 22
    public static function addCssClass(&$options, $class)
2006
    {
2007 22
        if (isset($options['class'])) {
2008 14
            if (is_array($options['class'])) {
2009 3
                $options['class'] = self::mergeCssClasses($options['class'], (array) $class);
2010
            } else {
2011 12
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
2012 14
                $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
0 ignored issues
show
Bug introduced by
It seems like $classes can also be of type false; however, parameter $existingClasses of yii\helpers\BaseHtml::mergeCssClasses() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2012
                $options['class'] = implode(' ', self::mergeCssClasses(/** @scrutinizer ignore-type */ $classes, (array) $class));
Loading history...
2013
            }
2014
        } else {
2015 15
            $options['class'] = $class;
2016
        }
2017 22
    }
2018
2019
    /**
2020
     * Merges already existing CSS classes with new one.
2021
     * This method provides the priority for named existing classes over additional.
2022
     * @param array $existingClasses already existing CSS classes.
2023
     * @param array $additionalClasses CSS classes to be added.
2024
     * @return array merge result.
2025
     * @see addCssClass()
2026
     */
2027 14
    private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
2028
    {
2029 14
        foreach ($additionalClasses as $key => $class) {
2030 14
            if (is_int($key) && !in_array($class, $existingClasses)) {
2031 13
                $existingClasses[] = $class;
2032 2
            } elseif (!isset($existingClasses[$key])) {
2033 14
                $existingClasses[$key] = $class;
2034
            }
2035
        }
2036
2037 14
        return array_unique($existingClasses);
2038
    }
2039
2040
    /**
2041
     * Removes a CSS class from the specified options.
2042
     * @param array $options the options to be modified.
2043
     * @param string|array $class the CSS class(es) to be removed
2044
     * @see addCssClass()
2045
     */
2046 1
    public static function removeCssClass(&$options, $class)
2047
    {
2048 1
        if (isset($options['class'])) {
2049 1
            if (is_array($options['class'])) {
2050 1
                $classes = array_diff($options['class'], (array) $class);
2051 1
                if (empty($classes)) {
2052 1
                    unset($options['class']);
2053
                } else {
2054 1
                    $options['class'] = $classes;
2055
                }
2056
            } else {
2057 1
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
2058 1
                $classes = array_diff($classes, (array) $class);
0 ignored issues
show
Bug introduced by
It seems like $classes can also be of type false; however, parameter $array1 of array_diff() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

2058
                $classes = array_diff(/** @scrutinizer ignore-type */ $classes, (array) $class);
Loading history...
2059 1
                if (empty($classes)) {
2060 1
                    unset($options['class']);
2061
                } else {
2062 1
                    $options['class'] = implode(' ', $classes);
2063
                }
2064
            }
2065
        }
2066 1
    }
2067
2068
    /**
2069
     * Adds the specified CSS style to the HTML options.
2070
     *
2071
     * If the options already contain a `style` element, the new style will be merged
2072
     * with the existing one. If a CSS property exists in both the new and the old styles,
2073
     * the old one may be overwritten if `$overwrite` is true.
2074
     *
2075
     * For example,
2076
     *
2077
     * ```php
2078
     * Html::addCssStyle($options, 'width: 100px; height: 200px');
2079
     * ```
2080
     *
2081
     * @param array $options the HTML options to be modified.
2082
     * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
2083
     * array (e.g. `['width' => '100px', 'height' => '200px']`).
2084
     * @param bool $overwrite whether to overwrite existing CSS properties if the new style
2085
     * contain them too.
2086
     * @see removeCssStyle()
2087
     * @see cssStyleFromArray()
2088
     * @see cssStyleToArray()
2089
     */
2090 1
    public static function addCssStyle(&$options, $style, $overwrite = true)
2091
    {
2092 1
        if (!empty($options['style'])) {
2093 1
            $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
2094 1
            $newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
2095 1
            if (!$overwrite) {
2096 1
                foreach ($newStyle as $property => $value) {
2097 1
                    if (isset($oldStyle[$property])) {
2098 1
                        unset($newStyle[$property]);
2099
                    }
2100
                }
2101
            }
2102 1
            $style = array_merge($oldStyle, $newStyle);
2103
        }
2104 1
        $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
2105 1
    }
2106
2107
    /**
2108
     * Removes the specified CSS style from the HTML options.
2109
     *
2110
     * For example,
2111
     *
2112
     * ```php
2113
     * Html::removeCssStyle($options, ['width', 'height']);
2114
     * ```
2115
     *
2116
     * @param array $options the HTML options to be modified.
2117
     * @param string|array $properties the CSS properties to be removed. You may use a string
2118
     * if you are removing a single property.
2119
     * @see addCssStyle()
2120
     */
2121 1
    public static function removeCssStyle(&$options, $properties)
2122
    {
2123 1
        if (!empty($options['style'])) {
2124 1
            $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
2125 1
            foreach ((array) $properties as $property) {
2126 1
                unset($style[$property]);
2127
            }
2128 1
            $options['style'] = static::cssStyleFromArray($style);
2129
        }
2130 1
    }
2131
2132
    /**
2133
     * Converts a CSS style array into a string representation.
2134
     *
2135
     * For example,
2136
     *
2137
     * ```php
2138
     * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
2139
     * // will display: 'width: 100px; height: 200px;'
2140
     * ```
2141
     *
2142
     * @param array $style the CSS style array. The array keys are the CSS property names,
2143
     * and the array values are the corresponding CSS property values.
2144
     * @return string the CSS style string. If the CSS style is empty, a null will be returned.
2145
     */
2146 4
    public static function cssStyleFromArray(array $style)
2147
    {
2148 4
        $result = '';
2149 4
        foreach ($style as $name => $value) {
2150 4
            $result .= "$name: $value; ";
2151
        }
2152
        // return null if empty to avoid rendering the "style" attribute
2153 4
        return $result === '' ? null : rtrim($result);
2154
    }
2155
2156
    /**
2157
     * Converts a CSS style string into an array representation.
2158
     *
2159
     * The array keys are the CSS property names, and the array values
2160
     * are the corresponding CSS property values.
2161
     *
2162
     * For example,
2163
     *
2164
     * ```php
2165
     * print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
2166
     * // will display: ['width' => '100px', 'height' => '200px']
2167
     * ```
2168
     *
2169
     * @param string $style the CSS style string
2170
     * @return array the array representation of the CSS style
2171
     */
2172 3
    public static function cssStyleToArray($style)
2173
    {
2174 3
        $result = [];
2175 3
        foreach (explode(';', $style) as $property) {
2176 3
            $property = explode(':', $property);
2177 3
            if (count($property) > 1) {
2178 3
                $result[trim($property[0])] = trim($property[1]);
2179
            }
2180
        }
2181
2182 3
        return $result;
2183
    }
2184
2185
    /**
2186
     * Returns the real attribute name from the given attribute expression.
2187
     *
2188
     * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
2189
     * It is mainly used in tabular data input and/or input of array type. Below are some examples:
2190
     *
2191
     * - `[0]content` is used in tabular data input to represent the "content" attribute
2192
     *   for the first model in tabular input;
2193
     * - `dates[0]` represents the first array element of the "dates" attribute;
2194
     * - `[0]dates[0]` represents the first array element of the "dates" attribute
2195
     *   for the first model in tabular input.
2196
     *
2197
     * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
2198
     * @param string $attribute the attribute name or expression
2199
     * @return string the attribute name without prefix and suffix.
2200
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2201
     */
2202 58
    public static function getAttributeName($attribute)
2203
    {
2204 58
        if (preg_match(static::$attributeRegex, $attribute, $matches)) {
2205 55
            return $matches[2];
2206
        }
2207
2208 3
        throw new InvalidArgumentException('Attribute name must contain word characters only.');
2209
    }
2210
2211
    /**
2212
     * Returns the value of the specified attribute name or expression.
2213
     *
2214
     * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
2215
     * See [[getAttributeName()]] for more details about attribute expression.
2216
     *
2217
     * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
2218
     * the primary value(s) of the AR instance(s) will be returned instead.
2219
     *
2220
     * @param Model $model the model object
2221
     * @param string $attribute the attribute name or expression
2222
     * @return string|array the corresponding attribute value
2223
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2224
     */
2225 51
    public static function getAttributeValue($model, $attribute)
2226
    {
2227 51
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2228 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2229
        }
2230 50
        $attribute = $matches[2];
2231 50
        $value = $model->$attribute;
2232 50
        if ($matches[3] !== '') {
2233
            foreach (explode('][', trim($matches[3], '[]')) as $id) {
2234
                if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
2235
                    $value = $value[$id];
2236
                } else {
2237
                    return null;
2238
                }
2239
            }
2240
        }
2241
2242
        // https://github.com/yiisoft/yii2/issues/1457
2243 50
        if (is_array($value)) {
2244
            foreach ($value as $i => $v) {
2245
                if ($v instanceof ActiveRecordInterface) {
2246
                    $v = $v->getPrimaryKey(false);
2247
                    $value[$i] = is_array($v) ? json_encode($v) : $v;
2248
                }
2249
            }
2250 50
        } elseif ($value instanceof ActiveRecordInterface) {
2251
            $value = $value->getPrimaryKey(false);
2252
2253
            return is_array($value) ? json_encode($value) : $value;
2254
        }
2255
2256 50
        return $value;
2257
    }
2258
2259
    /**
2260
     * Generates an appropriate input name for the specified attribute name or expression.
2261
     *
2262
     * This method generates a name that can be used as the input name to collect user input
2263
     * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
2264
     * of the model and the given attribute name. For example, if the form name of the `Post` model
2265
     * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
2266
     *
2267
     * See [[getAttributeName()]] for explanation of attribute expression.
2268
     *
2269
     * @param Model $model the model object
2270
     * @param string $attribute the attribute name or expression
2271
     * @return string the generated input name
2272
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2273
     */
2274 73
    public static function getInputName($model, $attribute)
2275
    {
2276 73
        $formName = $model->formName();
2277 73
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2278 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2279
        }
2280 72
        $prefix = $matches[1];
2281 72
        $attribute = $matches[2];
2282 72
        $suffix = $matches[3];
2283 72
        if ($formName === '' && $prefix === '') {
2284
            return $attribute . $suffix;
2285 72
        } elseif ($formName !== '') {
2286 72
            return $formName . $prefix . "[$attribute]" . $suffix;
2287
        }
2288
2289
        throw new InvalidArgumentException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
2290
    }
2291
2292
    /**
2293
     * Generates an appropriate input ID for the specified attribute name or expression.
2294
     *
2295
     * This method converts the result [[getInputName()]] into a valid input ID.
2296
     * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
2297
     * @param Model $model the model object
2298
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
2299
     * @return string the generated input ID
2300
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2301
     */
2302 68
    public static function getInputId($model, $attribute)
2303
    {
2304 68
        $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
2305 68
        $name = mb_strtolower(static::getInputName($model, $attribute), $charset);
2306 68
        return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
2307
    }
2308
2309
    /**
2310
     * Escapes regular expression to use in JavaScript.
2311
     * @param string $regexp the regular expression to be escaped.
2312
     * @return string the escaped result.
2313
     * @since 2.0.6
2314
     */
2315 1
    public static function escapeJsRegularExpression($regexp)
2316
    {
2317 1
        $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
2318 1
        $deliminator = substr($pattern, 0, 1);
2319 1
        $pos = strrpos($pattern, $deliminator, 1);
2320 1
        $flag = substr($pattern, $pos + 1);
2321 1
        if ($deliminator !== '/') {
2322 1
            $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
2323
        } else {
2324 1
            $pattern = substr($pattern, 0, $pos + 1);
2325
        }
2326 1
        if (!empty($flag)) {
2327 1
            $pattern .= preg_replace('/[^igmu]/', '', $flag);
2328
        }
2329
2330 1
        return $pattern;
2331
    }
2332
}
2333