Passed
Pull Request — master (#19681)
by Paweł
08:56
created

BaseHtml::getAttributeName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 7
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @link https://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license https://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 https://html.spec.whatwg.org/multipage/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 = ['aria', 'data', 'data-ng', 'ng'];
97
    /**
98
     * @var bool whether to removes duplicate class names in tag attribute `class`
99
     * @see mergeCssClasses()
100
     * @see renderTagAttributes()
101
     * @since 2.0.44
102
     */
103
    public static $normalizeClassAttribute = false;
104
105
106
    /**
107
     * Encodes special characters into HTML entities.
108
     * The [[\yii\base\Application::charset|application charset]] will be used for encoding.
109
     * @param string $content the content to be encoded
110
     * @param bool $doubleEncode whether to encode HTML entities in `$content`. If false,
111
     * HTML entities in `$content` will not be further encoded.
112
     * @return string the encoded content
113
     * @see decode()
114
     * @see https://www.php.net/manual/en/function.htmlspecialchars.php
115
     */
116 265
    public static function encode($content, $doubleEncode = true)
117
    {
118 265
        return htmlspecialchars((string)$content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode);
119
    }
120
121
    /**
122
     * Decodes special HTML entities back to the corresponding characters.
123
     * This is the opposite of [[encode()]].
124
     * @param string $content the content to be decoded
125
     * @return string the decoded content
126
     * @see encode()
127
     * @see https://www.php.net/manual/en/function.htmlspecialchars-decode.php
128
     */
129 1
    public static function decode($content)
130
    {
131 1
        return htmlspecialchars_decode($content, ENT_QUOTES);
132
    }
133
134
    /**
135
     * Generates a complete HTML tag.
136
     * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
137
     * @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded.
138
     * If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks.
139
     * @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs.
140
     * These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
141
     * If a value is null, the corresponding attribute will not be rendered.
142
     *
143
     * For example when using `['class' => 'my-class', 'target' => '_blank', 'value' => null]` it will result in the
144
     * html attributes rendered like this: `class="my-class" target="_blank"`.
145
     *
146
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
147
     *
148
     * @return string the generated HTML tag
149
     * @see beginTag()
150
     * @see endTag()
151
     */
152 251
    public static function tag($name, $content = '', $options = [])
153
    {
154 251
        if ($name === null || $name === false) {
155 3
            return $content;
156
        }
157 250
        $html = "<$name" . static::renderTagAttributes($options) . '>';
158 250
        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 $string 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

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

986
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, /** @scrutinizer ignore-type */ $selection)
Loading history...
987 4
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, $selection, $strict));
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 iterable, 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

987
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, /** @scrutinizer ignore-type */ $selection, $strict));
Loading history...
988 4
            if ($formatter !== null) {
989 1
                $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
990
            } else {
991 4
                $lines[] = static::checkbox($name, $checked, array_merge([
992 4
                    'value' => $value,
993 4
                    'label' => $encode ? static::encode($label) : $label,
994
                ], $itemOptions));
0 ignored issues
show
Bug introduced by
It seems like $itemOptions can also be of type null; however, parameter $arrays of array_merge() 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

994
                ], /** @scrutinizer ignore-type */ $itemOptions));
Loading history...
995
            }
996 4
            $index++;
997
        }
998
999 4
        if (isset($options['unselect'])) {
1000
            // add a hidden field so that if the list box has no option being selected, it still submits a value
1001 3
            $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
1002 3
            $hiddenOptions = [];
1003
            // make sure disabled input is not sending any value
1004 3
            if (!empty($options['disabled'])) {
1005 1
                $hiddenOptions['disabled'] = $options['disabled'];
1006
            }
1007 3
            $hidden = static::hiddenInput($name2, $options['unselect'], $hiddenOptions);
1008 3
            unset($options['unselect'], $options['disabled']);
1009
        } else {
1010 2
            $hidden = '';
1011
        }
1012
1013 4
        $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

1013
        $visibleContent = implode(/** @scrutinizer ignore-type */ $separator, $lines);
Loading history...
1014
1015 4
        if ($tag === false) {
1016 1
            return $hidden . $visibleContent;
1017
        }
1018
1019 4
        return $hidden . static::tag($tag, $visibleContent, $options);
1020
    }
1021
1022
    /**
1023
     * Generates a list of radio buttons.
1024
     * A radio button list is like a checkbox list, except that it only allows single selection.
1025
     * @param string $name the name attribute of each radio button.
1026
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
1027
     * @param array $items the data item used to generate the radio buttons.
1028
     * The array keys are the radio button values, while the array values are the corresponding labels.
1029
     * @param array $options options (name => config) for the radio button list container tag.
1030
     * The following options are specially handled:
1031
     *
1032
     * - tag: string|false, the tag name of the container element. False to render radio buttons without container.
1033
     *   See also [[tag()]].
1034
     * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
1035
     *   By setting this option, a hidden input will be generated.
1036
     * - disabled: boolean, whether the generated by unselect option hidden input should be disabled. Defaults to false.
1037
     *   This option is available since version 2.0.16.
1038
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1039
     *   This option is ignored if `item` option is set.
1040
     * - strict: boolean, if `$selection` is an array and this value is true a strict comparison will be performed on `$items` keys. Defaults to false.
1041
     *   This option is available since 2.0.37.
1042
     * - separator: string, the HTML code that separates items.
1043
     * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
1044
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1045
     *   corresponding to a single item in $items. The signature of this callback must be:
1046
     *
1047
     *   ```php
1048
     *   function ($index, $label, $name, $checked, $value)
1049
     *   ```
1050
     *
1051
     *   where $index is the zero-based index of the radio button in the whole list; $label
1052
     *   is the label for the radio button; and $name, $value and $checked represent the name,
1053
     *   value and the checked status of the radio button input, respectively.
1054
     *
1055
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1056
     *
1057
     * @return string the generated radio button list
1058
     */
1059 4
    public static function radioList($name, $selection = null, $items = [], $options = [])
1060
    {
1061 4
        if (ArrayHelper::isTraversable($selection)) {
1062 2
            $selection = array_map('strval', ArrayHelper::toArray($selection));
1063
        }
1064
1065 4
        $formatter = ArrayHelper::remove($options, 'item');
1066 4
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
1067 4
        $encode = ArrayHelper::remove($options, 'encode', true);
1068 4
        $separator = ArrayHelper::remove($options, 'separator', "\n");
1069 4
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1070 4
        $strict = ArrayHelper::remove($options, 'strict', false);
1071
1072 4
        $hidden = '';
1073 4
        if (isset($options['unselect'])) {
1074
            // add a hidden field so that if the list box has no option being selected, it still submits a value
1075 3
            $hiddenOptions = [];
1076
            // make sure disabled input is not sending any value
1077 3
            if (!empty($options['disabled'])) {
1078 1
                $hiddenOptions['disabled'] = $options['disabled'];
1079
            }
1080 3
            $hidden =  static::hiddenInput($name, $options['unselect'], $hiddenOptions);
1081 3
            unset($options['unselect'], $options['disabled']);
1082
        }
1083
1084 4
        $lines = [];
1085 4
        $index = 0;
1086 4
        foreach ($items as $value => $label) {
1087 4
            $checked = $selection !== null &&
1088 2
                (!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 $string2 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

1088
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, /** @scrutinizer ignore-type */ $selection)
Loading history...
1089 4
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, $selection, $strict));
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 iterable, 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

1089
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$value, /** @scrutinizer ignore-type */ $selection, $strict));
Loading history...
1090 4
            if ($formatter !== null) {
1091 1
                $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
1092
            } else {
1093 4
                $lines[] = static::radio($name, $checked, array_merge([
1094 4
                    'value' => $value,
1095 4
                    'label' => $encode ? static::encode($label) : $label,
1096
                ], $itemOptions));
0 ignored issues
show
Bug introduced by
It seems like $itemOptions can also be of type null; however, parameter $arrays of array_merge() 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

1096
                ], /** @scrutinizer ignore-type */ $itemOptions));
Loading history...
1097
            }
1098 4
            $index++;
1099
        }
1100 4
        $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

1100
        $visibleContent = implode(/** @scrutinizer ignore-type */ $separator, $lines);
Loading history...
1101
1102 4
        if ($tag === false) {
1103 1
            return $hidden . $visibleContent;
1104
        }
1105
1106 4
        return $hidden . static::tag($tag, $visibleContent, $options);
1107
    }
1108
1109
    /**
1110
     * Generates an unordered list.
1111
     * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
1112
     * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
1113
     * @param array $options options (name => config) for the radio button list. The following options are supported:
1114
     *
1115
     * - encode: boolean, whether to HTML-encode the items. Defaults to true.
1116
     *   This option is ignored if the `item` option is specified.
1117
     * - separator: string, the HTML code that separates items. Defaults to a simple newline (`"\n"`).
1118
     *   This option is available since version 2.0.7.
1119
     * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
1120
     * - item: callable, a callback that is used to generate each individual list item.
1121
     *   The signature of this callback must be:
1122
     *
1123
     *   ```php
1124
     *   function ($item, $index)
1125
     *   ```
1126
     *
1127
     *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
1128
     *   the whole list item tag.
1129
     *
1130
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1131
     *
1132
     * @return string the generated unordered list. An empty list tag will be returned if `$items` is empty.
1133
     */
1134 5
    public static function ul($items, $options = [])
1135
    {
1136 5
        $tag = ArrayHelper::remove($options, 'tag', 'ul');
1137 5
        $encode = ArrayHelper::remove($options, 'encode', true);
1138 5
        $formatter = ArrayHelper::remove($options, 'item');
1139 5
        $separator = ArrayHelper::remove($options, 'separator', "\n");
1140 5
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
1141
1142 5
        if (empty($items)) {
1143 2
            return static::tag($tag, '', $options);
1144
        }
1145
1146 5
        $results = [];
1147 5
        foreach ($items as $index => $item) {
1148 5
            if ($formatter !== null) {
1149 2
                $results[] = call_user_func($formatter, $item, $index);
1150
            } else {
1151 5
                $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
1152
            }
1153
        }
1154
1155 5
        return static::tag(
1156 5
            $tag,
1157 5
            $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

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

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

1932
                            $selected = ArrayHelper::isIn((string)$key, /** @scrutinizer ignore-type */ $selection, $strict);
Loading history...
1933 19
                        } elseif ($key === '' || $selection === '') {
1934 14
                            $selected = $selection === $key;
1935 17
                        } elseif ($strict) {
1936 7
                            $selected = !strcmp((string)$key, (string)$selection);
1937
                        } else {
1938 11
                            $selected = $selection == $key;
1939
                        }
1940
                    }
1941
1942 24
                    $attrs['selected'] = $selected;
1943
                }
1944 24
                $text = $encode ? static::encode($value) : $value;
1945 24
                if ($encodeSpaces) {
1946 2
                    $text = str_replace(' ', '&nbsp;', $text);
1947
                }
1948 24
                $lines[] = static::tag('option', $text, $attrs);
1949
            }
1950
        }
1951
1952 25
        return implode("\n", $lines);
1953
    }
1954
1955
    /**
1956
     * Renders the HTML tag attributes.
1957
     *
1958
     * Attributes whose values are of boolean type will be treated as
1959
     * [boolean attributes](https://html.spec.whatwg.org/multipage/common-microsyntaxes.html#boolean-attributes).
1960
     *
1961
     * Attributes whose values are null will not be rendered.
1962
     *
1963
     * The values of attributes will be HTML-encoded using [[encode()]].
1964
     *
1965
     * `aria` and `data` attributes get special handling when they are set to an array value. In these cases,
1966
     * the array will be "expanded" and a list of ARIA/data attributes will be rendered. For example,
1967
     * `'aria' => ['role' => 'checkbox', 'value' => 'true']` would be rendered as
1968
     * `aria-role="checkbox" aria-value="true"`.
1969
     *
1970
     * If a nested `data` value is set to an array, it will be JSON-encoded. For example,
1971
     * `'data' => ['params' => ['id' => 1, 'name' => 'yii']]` would be rendered as
1972
     * `data-params='{"id":1,"name":"yii"}'`.
1973
     *
1974
     * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
1975
     * @return string the rendering result. If the attributes are not empty, they will be rendered
1976
     * into a string with a leading white space (so that it can be directly appended to the tag name
1977
     * in a tag). If there is no attribute, an empty string will be returned.
1978
     * @see addCssClass()
1979
     */
1980 261
    public static function renderTagAttributes($attributes)
1981
    {
1982 261
        if (count($attributes) > 1) {
1983 205
            $sorted = [];
1984 205
            foreach (static::$attributeOrder as $name) {
1985 205
                if (isset($attributes[$name])) {
1986 205
                    $sorted[$name] = $attributes[$name];
1987
                }
1988
            }
1989 205
            $attributes = array_merge($sorted, $attributes);
1990
        }
1991
1992 261
        $html = '';
1993 261
        foreach ($attributes as $name => $value) {
1994 250
            if (is_bool($value)) {
1995 58
                if ($value) {
1996 58
                    $html .= " $name";
1997
                }
1998 250
            } elseif (is_array($value)) {
1999 11
                if (in_array($name, static::$dataAttributes)) {
2000 3
                    foreach ($value as $n => $v) {
2001 3
                        if (is_array($v)) {
2002 1
                            $html .= " $name-$n='" . Json::htmlEncode($v) . "'";
2003 3
                        } elseif (is_bool($v)) {
2004 1
                            if ($v) {
2005 1
                                $html .= " $name-$n";
2006
                            }
2007 3
                        } elseif ($v !== null) {
2008 2
                            $html .= " $name-$n=\"" . static::encode($v) . '"';
2009
                        }
2010
                    }
2011 10
                } elseif ($name === 'class') {
2012 9
                    if (empty($value)) {
2013 8
                        continue;
2014
                    }
2015 4
                    if (static::$normalizeClassAttribute === true && count($value) > 1) {
2016
                        // removes duplicate classes
2017 2
                        $value = explode(' ', implode(' ', $value));
2018 2
                        $value = array_unique($value);
2019
                    }
2020 4
                    $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
2021 2
                } elseif ($name === 'style') {
2022 1
                    if (empty($value)) {
2023 1
                        continue;
2024
                    }
2025 1
                    $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
2026
                } else {
2027 6
                    $html .= " $name='" . Json::htmlEncode($value) . "'";
2028
                }
2029 244
            } elseif ($value !== null) {
2030 244
                $html .= " $name=\"" . static::encode($value) . '"';
2031
            }
2032
        }
2033
2034 261
        return $html;
2035
    }
2036
2037
    /**
2038
     * Adds a CSS class (or several classes) to the specified options.
2039
     *
2040
     * If the CSS class is already in the options, it will not be added again.
2041
     * If class specification at given options is an array, and some class placed there with the named (string) key,
2042
     * overriding of such key will have no effect. For example:
2043
     *
2044
     * ```php
2045
     * $options = ['class' => ['persistent' => 'initial']];
2046
     * Html::addCssClass($options, ['persistent' => 'override']);
2047
     * var_dump($options['class']); // outputs: array('persistent' => 'initial');
2048
     * ```
2049
     *
2050
     * @param array $options the options to be modified.
2051
     * @param string|array $class the CSS class(es) to be added
2052
     * @see removeCssClass()
2053
     */
2054 23
    public static function addCssClass(&$options, $class)
2055
    {
2056 23
        if (isset($options['class'])) {
2057 15
            if (is_array($options['class'])) {
2058 3
                $options['class'] = self::mergeCssClasses($options['class'], (array) $class);
2059
            } else {
2060 13
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
2061 15
                $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
2062
            }
2063
        } else {
2064 16
            $options['class'] = $class;
2065
        }
2066 23
    }
2067
2068
    /**
2069
     * Merges already existing CSS classes with new one.
2070
     * This method provides the priority for named existing classes over additional.
2071
     * @param array $existingClasses already existing CSS classes.
2072
     * @param array $additionalClasses CSS classes to be added.
2073
     * @return array merge result.
2074
     * @see addCssClass()
2075
     */
2076 15
    private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
2077
    {
2078 15
        foreach ($additionalClasses as $key => $class) {
2079 15
            if (is_int($key) && !in_array($class, $existingClasses)) {
2080 14
                $existingClasses[] = $class;
2081 2
            } elseif (!isset($existingClasses[$key])) {
2082 1
                $existingClasses[$key] = $class;
2083
            }
2084
        }
2085
2086 15
        return static::$normalizeClassAttribute ? array_unique($existingClasses) : $existingClasses;
2087
    }
2088
2089
    /**
2090
     * Removes a CSS class from the specified options.
2091
     * @param array $options the options to be modified.
2092
     * @param string|array $class the CSS class(es) to be removed
2093
     * @see addCssClass()
2094
     */
2095 1
    public static function removeCssClass(&$options, $class)
2096
    {
2097 1
        if (isset($options['class'])) {
2098 1
            if (is_array($options['class'])) {
2099 1
                $classes = array_diff($options['class'], (array) $class);
2100 1
                if (empty($classes)) {
2101 1
                    unset($options['class']);
2102
                } else {
2103 1
                    $options['class'] = $classes;
2104
                }
2105
            } else {
2106 1
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
2107 1
                $classes = array_diff($classes, (array) $class);
2108 1
                if (empty($classes)) {
2109 1
                    unset($options['class']);
2110
                } else {
2111 1
                    $options['class'] = implode(' ', $classes);
2112
                }
2113
            }
2114
        }
2115 1
    }
2116
2117
    /**
2118
     * Adds the specified CSS style to the HTML options.
2119
     *
2120
     * If the options already contain a `style` element, the new style will be merged
2121
     * with the existing one. If a CSS property exists in both the new and the old styles,
2122
     * the old one may be overwritten if `$overwrite` is true.
2123
     *
2124
     * For example,
2125
     *
2126
     * ```php
2127
     * Html::addCssStyle($options, 'width: 100px; height: 200px');
2128
     * ```
2129
     *
2130
     * @param array $options the HTML options to be modified.
2131
     * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
2132
     * array (e.g. `['width' => '100px', 'height' => '200px']`).
2133
     * @param bool $overwrite whether to overwrite existing CSS properties if the new style
2134
     * contain them too.
2135
     * @see removeCssStyle()
2136
     * @see cssStyleFromArray()
2137
     * @see cssStyleToArray()
2138
     */
2139 1
    public static function addCssStyle(&$options, $style, $overwrite = true)
2140
    {
2141 1
        if (!empty($options['style'])) {
2142 1
            $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
2143 1
            $newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
2144 1
            if (!$overwrite) {
2145 1
                foreach ($newStyle as $property => $value) {
2146 1
                    if (isset($oldStyle[$property])) {
2147 1
                        unset($newStyle[$property]);
2148
                    }
2149
                }
2150
            }
2151 1
            $style = array_merge($oldStyle, $newStyle);
2152
        }
2153 1
        $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
2154 1
    }
2155
2156
    /**
2157
     * Removes the specified CSS style from the HTML options.
2158
     *
2159
     * For example,
2160
     *
2161
     * ```php
2162
     * Html::removeCssStyle($options, ['width', 'height']);
2163
     * ```
2164
     *
2165
     * @param array $options the HTML options to be modified.
2166
     * @param string|array $properties the CSS properties to be removed. You may use a string
2167
     * if you are removing a single property.
2168
     * @see addCssStyle()
2169
     */
2170 1
    public static function removeCssStyle(&$options, $properties)
2171
    {
2172 1
        if (!empty($options['style'])) {
2173 1
            $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
2174 1
            foreach ((array) $properties as $property) {
2175 1
                unset($style[$property]);
2176
            }
2177 1
            $options['style'] = static::cssStyleFromArray($style);
2178
        }
2179 1
    }
2180
2181
    /**
2182
     * Converts a CSS style array into a string representation.
2183
     *
2184
     * For example,
2185
     *
2186
     * ```php
2187
     * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
2188
     * // will display: 'width: 100px; height: 200px;'
2189
     * ```
2190
     *
2191
     * @param array $style the CSS style array. The array keys are the CSS property names,
2192
     * and the array values are the corresponding CSS property values.
2193
     * @return string the CSS style string. If the CSS style is empty, a null will be returned.
2194
     */
2195 4
    public static function cssStyleFromArray(array $style)
2196
    {
2197 4
        $result = '';
2198 4
        foreach ($style as $name => $value) {
2199 4
            $result .= "$name: $value; ";
2200
        }
2201
        // return null if empty to avoid rendering the "style" attribute
2202 4
        return $result === '' ? null : rtrim($result);
2203
    }
2204
2205
    /**
2206
     * Converts a CSS style string into an array representation.
2207
     *
2208
     * The array keys are the CSS property names, and the array values
2209
     * are the corresponding CSS property values.
2210
     *
2211
     * For example,
2212
     *
2213
     * ```php
2214
     * print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
2215
     * // will display: ['width' => '100px', 'height' => '200px']
2216
     * ```
2217
     *
2218
     * @param string $style the CSS style string
2219
     * @return array the array representation of the CSS style
2220
     */
2221 3
    public static function cssStyleToArray($style)
2222
    {
2223 3
        $result = [];
2224 3
        foreach (explode(';', $style) as $property) {
2225 3
            $property = explode(':', $property);
2226 3
            if (count($property) > 1) {
2227 3
                $result[trim($property[0])] = trim($property[1]);
2228
            }
2229
        }
2230
2231 3
        return $result;
2232
    }
2233
2234
    /**
2235
     * Returns the real attribute name from the given attribute expression.
2236
     *
2237
     * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
2238
     * It is mainly used in tabular data input and/or input of array type. Below are some examples:
2239
     *
2240
     * - `[0]content` is used in tabular data input to represent the "content" attribute
2241
     *   for the first model in tabular input;
2242
     * - `dates[0]` represents the first array element of the "dates" attribute;
2243
     * - `[0]dates[0]` represents the first array element of the "dates" attribute
2244
     *   for the first model in tabular input.
2245
     *
2246
     * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
2247
     * @param string $attribute the attribute name or expression
2248
     * @return string the attribute name without prefix and suffix.
2249
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2250
     */
2251 69
    public static function getAttributeName($attribute)
2252
    {
2253 69
        if (preg_match(static::$attributeRegex, $attribute, $matches)) {
2254 66
            return $matches[2];
2255
        }
2256
2257 3
        throw new InvalidArgumentException('Attribute name must contain word characters only.');
2258
    }
2259
2260
    /**
2261
     * Returns the value of the specified attribute name or expression.
2262
     *
2263
     * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
2264
     * See [[getAttributeName()]] for more details about attribute expression.
2265
     *
2266
     * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
2267
     * the primary value(s) of the AR instance(s) will be returned instead.
2268
     *
2269
     * @param Model $model the model object
2270
     * @param string $attribute the attribute name or expression
2271
     * @return string|array the corresponding attribute value
2272
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2273
     */
2274 60
    public static function getAttributeValue($model, $attribute)
2275
    {
2276 60
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2277 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2278
        }
2279 59
        $attribute = $matches[2];
2280 59
        $value = $model->$attribute;
2281 59
        if ($matches[3] !== '') {
2282
            foreach (explode('][', trim($matches[3], '[]')) as $id) {
2283
                if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
2284
                    $value = $value[$id];
2285
                } else {
2286
                    return null;
2287
                }
2288
            }
2289
        }
2290
2291
        // https://github.com/yiisoft/yii2/issues/1457
2292 59
        if (is_array($value)) {
2293 1
            foreach ($value as $i => $v) {
2294 1
                if ($v instanceof ActiveRecordInterface) {
2295 1
                    $v = $v->getPrimaryKey(false);
2296 1
                    $value[$i] = is_array($v) ? json_encode($v) : $v;
2297
                }
2298
            }
2299 59
        } elseif ($value instanceof ActiveRecordInterface) {
2300 1
            $value = $value->getPrimaryKey(false);
2301
2302 1
            return is_array($value) ? json_encode($value) : $value;
2303
        }
2304
2305 59
        return $value;
2306
    }
2307
2308
    /**
2309
     * Generates an appropriate input name for the specified attribute name or expression.
2310
     *
2311
     * This method generates a name that can be used as the input name to collect user input
2312
     * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
2313
     * of the model and the given attribute name. For example, if the form name of the `Post` model
2314
     * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
2315
     *
2316
     * See [[getAttributeName()]] for explanation of attribute expression.
2317
     *
2318
     * @param Model $model the model object
2319
     * @param string $attribute the attribute name or expression
2320
     * @return string the generated input name
2321
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2322
     */
2323 93
    public static function getInputName($model, $attribute)
2324
    {
2325 93
        $formName = $model->formName();
2326 93
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2327 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2328
        }
2329 92
        $prefix = $matches[1];
2330 92
        $attribute = $matches[2];
2331 92
        $suffix = $matches[3];
2332 92
        if ($formName === '' && $prefix === '') {
2333 1
            return $attribute . $suffix;
2334 91
        } elseif ($formName !== '') {
2335 90
            return $formName . $prefix . "[$attribute]" . $suffix;
2336
        }
2337
2338 1
        throw new InvalidArgumentException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
2339
    }
2340
2341
    /**
2342
     * Converts input name to ID.
2343
     *
2344
     * For example, if `$name` is `Post[content]`, this method will return `post-content`.
2345
     *
2346
     * @param string $name the input name
2347
     * @return string the generated input ID
2348
     * @since 2.0.43
2349
     */
2350 82
    public static function getInputIdByName($name)
2351
    {
2352 82
        $charset = Yii::$app ? Yii::$app->charset : 'UTF-8';
2353 82
        $name = mb_strtolower($name, $charset);
2354 82
        return str_replace(['[]', '][', '[', ']', ' ', '.', '--'], ['', '-', '-', '', '-', '-', '-'], $name);
2355
    }
2356
2357
    /**
2358
     * Generates an appropriate input ID for the specified attribute name or expression.
2359
     *
2360
     * @param Model $model the model object
2361
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
2362
     * @return string the generated input ID.
2363
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2364
     */
2365 74
    public static function getInputId($model, $attribute)
2366
    {
2367 74
        $name = static::getInputName($model, $attribute);
2368 74
        return static::getInputIdByName($name);
2369
    }
2370
2371
    /**
2372
     * Escapes regular expression to use in JavaScript.
2373
     * @param string $regexp the regular expression to be escaped.
2374
     * @return string the escaped result.
2375
     * @since 2.0.6
2376
     */
2377 1
    public static function escapeJsRegularExpression($regexp)
2378
    {
2379 1
        $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
2380 1
        $deliminator = substr($pattern, 0, 1);
2381 1
        $pos = strrpos($pattern, $deliminator, 1);
2382 1
        $flag = substr($pattern, $pos + 1);
2383 1
        if ($deliminator !== '/') {
2384 1
            $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
2385
        } else {
2386 1
            $pattern = substr($pattern, 0, $pos + 1);
2387
        }
2388 1
        if (!empty($flag)) {
2389 1
            $pattern .= preg_replace('/[^igmu]/', '', $flag);
2390
        }
2391
2392 1
        return $pattern;
2393
    }
2394
}
2395