Completed
Push — master ( 113152...f3438c )
by Alexander
14:06
created

BaseHtml::radioList()   C

Complexity

Conditions 12
Paths 156

Size

Total Lines 48

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 12

Importance

Changes 0
Metric Value
dl 0
loc 48
ccs 32
cts 32
cp 1
rs 6.4999
c 0
b 0
f 0
cc 12
nc 156
nop 4
crap 12

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

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

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1069 3
            if ($formatter !== null) {
1070 1
                $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
1071
            } else {
1072 3
                $lines[] = static::radio($name, $checked, array_merge([
1073 3
                    'value' => $value,
1074 3
                    'label' => $encode ? static::encode($label) : $label,
1075 3
                ], $itemOptions));
1076
            }
1077 3
            $index++;
1078
        }
1079 3
        $visibleContent = implode($separator, $lines);
1080
1081 3
        if ($tag === false) {
1082 1
            return $hidden . $visibleContent;
1083
        }
1084
1085 3
        return $hidden . static::tag($tag, $visibleContent, $options);
1086
    }
1087
1088
    /**
1089
     * Generates an unordered list.
1090
     * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
1091
     * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
1092
     * @param array $options options (name => config) for the radio button list. The following options are supported:
1093
     *
1094
     * - encode: boolean, whether to HTML-encode the items. Defaults to true.
1095
     *   This option is ignored if the `item` option is specified.
1096
     * - separator: string, the HTML code that separates items. Defaults to a simple newline (`"\n"`).
1097
     *   This option is available since version 2.0.7.
1098
     * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
1099
     * - item: callable, a callback that is used to generate each individual list item.
1100
     *   The signature of this callback must be:
1101
     *
1102
     *   ```php
1103
     *   function ($item, $index)
1104
     *   ```
1105
     *
1106
     *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
1107
     *   the whole list item tag.
1108
     *
1109
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1110
     *
1111
     * @return string the generated unordered list. An empty list tag will be returned if `$items` is empty.
1112
     */
1113 4
    public static function ul($items, $options = [])
1114
    {
1115 4
        $tag = ArrayHelper::remove($options, 'tag', 'ul');
1116 4
        $encode = ArrayHelper::remove($options, 'encode', true);
1117 4
        $formatter = ArrayHelper::remove($options, 'item');
1118 4
        $separator = ArrayHelper::remove($options, 'separator', "\n");
1119 4
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
1120
1121 4
        if (empty($items)) {
1122 2
            return static::tag($tag, '', $options);
1123
        }
1124
1125 4
        $results = [];
1126 4
        foreach ($items as $index => $item) {
1127 4
            if ($formatter !== null) {
1128 2
                $results[] = call_user_func($formatter, $item, $index);
1129
            } else {
1130 4
                $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
1131
            }
1132
        }
1133
1134 4
        return static::tag(
1135 4
            $tag,
1136 4
            $separator . implode($separator, $results) . $separator,
1137 4
            $options
1138
        );
1139
    }
1140
1141
    /**
1142
     * Generates an ordered list.
1143
     * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
1144
     * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
1145
     * @param array $options options (name => config) for the radio button list. The following options are supported:
1146
     *
1147
     * - encode: boolean, whether to HTML-encode the items. Defaults to true.
1148
     *   This option is ignored if the `item` option is specified.
1149
     * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
1150
     * - item: callable, a callback that is used to generate each individual list item.
1151
     *   The signature of this callback must be:
1152
     *
1153
     *   ```php
1154
     *   function ($item, $index)
1155
     *   ```
1156
     *
1157
     *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
1158
     *   the whole list item tag.
1159
     *
1160
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1161
     *
1162
     * @return string the generated ordered list. An empty string is returned if `$items` is empty.
1163
     */
1164 1
    public static function ol($items, $options = [])
1165
    {
1166 1
        $options['tag'] = 'ol';
1167 1
        return static::ul($items, $options);
1168
    }
1169
1170
    /**
1171
     * Generates a label tag for the given model attribute.
1172
     * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
1173
     * @param Model $model the model object
1174
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1175
     * about attribute expression.
1176
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1177
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1178
     * If a value is null, the corresponding attribute will not be rendered.
1179
     * The following options are specially handled:
1180
     *
1181
     * - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
1182
     *   If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
1183
     *   (after encoding).
1184
     *
1185
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1186
     *
1187
     * @return string the generated label tag
1188
     */
1189 13
    public static function activeLabel($model, $attribute, $options = [])
1190
    {
1191 13
        $for = ArrayHelper::remove($options, 'for', static::getInputId($model, $attribute));
1192 13
        $attribute = static::getAttributeName($attribute);
1193 13
        $label = ArrayHelper::remove($options, 'label', static::encode($model->getAttributeLabel($attribute)));
1194 13
        return static::label($label, $for, $options);
1195
    }
1196
1197
    /**
1198
     * Generates a hint tag for the given model attribute.
1199
     * The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]].
1200
     * If no hint content can be obtained, method will return an empty string.
1201
     * @param Model $model the model object
1202
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1203
     * about attribute expression.
1204
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1205
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1206
     * If a value is null, the corresponding attribute will not be rendered.
1207
     * The following options are specially handled:
1208
     *
1209
     * - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]].
1210
     *   If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display
1211
     *   (without encoding).
1212
     *
1213
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1214
     *
1215
     * @return string the generated hint tag
1216
     * @since 2.0.4
1217
     */
1218 13
    public static function activeHint($model, $attribute, $options = [])
1219
    {
1220 13
        $attribute = static::getAttributeName($attribute);
1221 13
        $hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute);
1222 13
        if (empty($hint)) {
1223 4
            return '';
1224
        }
1225 9
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1226 9
        unset($options['hint']);
1227 9
        return static::tag($tag, $hint, $options);
1228
    }
1229
1230
    /**
1231
     * Generates a summary of the validation errors.
1232
     * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
1233
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
1234
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1235
     *
1236
     * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
1237
     * - footer: string, the footer HTML for the error summary. Defaults to empty string.
1238
     * - encode: boolean, if set to false then the error messages won't be encoded. Defaults to `true`.
1239
     * - showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise
1240
     *   only the first error message for each attribute will be shown. Defaults to `false`.
1241
     *   Option is available since 2.0.10.
1242
     *
1243
     * The rest of the options will be rendered as the attributes of the container tag.
1244
     *
1245
     * @return string the generated error summary
1246
     */
1247 8
    public static function errorSummary($models, $options = [])
1248
    {
1249 8
        $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
1250 8
        $footer = ArrayHelper::remove($options, 'footer', '');
1251 8
        $encode = ArrayHelper::remove($options, 'encode', true);
1252 8
        $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
1253 8
        unset($options['header']);
1254 8
        $lines = self::collectErrors($models, $encode, $showAllErrors);
1255 8
        if (empty($lines)) {
1256
            // still render the placeholder for client-side validation use
1257 2
            $content = '<ul></ul>';
1258 2
            $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
1259
        } else {
1260 6
            $content = '<ul><li>' . implode("</li>\n<li>", $lines) . '</li></ul>';
1261
        }
1262
1263 8
        return Html::tag('div', $header . $content . $footer, $options);
1264
    }
1265
1266
    /**
1267
     * Return array of the validation errors
1268
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
1269
     * @param $encode boolean, if set to false then the error messages won't be encoded.
1270
     * @param $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
1271
     * only the first error message for each attribute will be shown.
1272
     * @return array of the validation errors
1273
     * @since 2.0.14
1274
     */
1275 8
    private static function collectErrors($models, $encode, $showAllErrors)
1276
    {
1277 8
        $lines = [];
1278 8
        if (!is_array($models)) {
1279 8
            $models = [$models];
1280
        }
1281
1282 8
        foreach ($models as $model) {
1283 8
            $lines = array_unique(array_merge($lines, $model->getErrorSummary($showAllErrors)));
1284
        }
1285
1286
        // If there are the same error messages for different attributes, array_unique will leave gaps
1287
        // between sequential keys. Applying array_values to reorder array keys.
1288 8
        $lines = array_values($lines);
1289
1290 8
        if ($encode) {
1291 7
            foreach ($lines as &$line) {
1292 5
                $line = Html::encode($line);
1293
            }
1294
        }
1295
1296 8
        return $lines;
1297
    }
1298
1299
    /**
1300
     * Generates a tag that contains the first validation error of the specified model attribute.
1301
     * Note that even if there is no validation error, this method will still return an empty error tag.
1302
     * @param Model $model the model object
1303
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1304
     * about attribute expression.
1305
     * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
1306
     * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1307
     *
1308
     * The following options are specially handled:
1309
     *
1310
     * - tag: this specifies the tag name. If not set, "div" will be used.
1311
     *   See also [[tag()]].
1312
     * - encode: boolean, if set to false then the error message won't be encoded.
1313
     * - errorSource (since 2.0.14): \Closure|callable, callback that will be called to obtain an error message.
1314
     *   The signature of the callback must be: `function ($model, $attribute)` and return a string.
1315
     *   When not set, the `$model->getFirstError()` method will be called.
1316
     *
1317
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1318
     *
1319
     * @return string the generated label tag
1320
     */
1321 12
    public static function error($model, $attribute, $options = [])
1322
    {
1323 12
        $attribute = static::getAttributeName($attribute);
1324 12
        $errorSource = ArrayHelper::remove($options, 'errorSource');
1325 12
        if ($errorSource !== null) {
1326 1
            $error = call_user_func($errorSource, $model, $attribute);
1327
        } else {
1328 12
            $error = $model->getFirstError($attribute);
1329
        }
1330 12
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1331 12
        $encode = ArrayHelper::remove($options, 'encode', true);
1332 12
        return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
1333
    }
1334
1335
    /**
1336
     * Generates an input tag for the given model attribute.
1337
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1338
     * unless they are explicitly specified in `$options`.
1339
     * @param string $type the input type (e.g. 'text', 'password')
1340
     * @param Model $model the model object
1341
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1342
     * about attribute expression.
1343
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1344
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1345
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1346
     * @return string the generated input tag
1347
     */
1348 30
    public static function activeInput($type, $model, $attribute, $options = [])
1349
    {
1350 30
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1351 30
        $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1352 30
        if (!array_key_exists('id', $options)) {
1353 28
            $options['id'] = static::getInputId($model, $attribute);
1354
        }
1355
1356 30
        static::setActivePlaceholder($model, $attribute, $options);
1357 30
        self::normalizeMaxLength($model, $attribute, $options);
1358
1359 30
        return static::input($type, $name, $value, $options);
1360
    }
1361
1362
    /**
1363
     * If `maxlength` option is set true and the model attribute is validated by a string validator,
1364
     * the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1365
     * @param Model $model the model object
1366
     * @param string $attribute the attribute name or expression.
1367
     * @param array $options the tag options in terms of name-value pairs.
1368
     */
1369 34
    private static function normalizeMaxLength($model, $attribute, &$options)
1370
    {
1371 34
        if (isset($options['maxlength']) && $options['maxlength'] === true) {
1372 4
            unset($options['maxlength']);
1373 4
            $attrName = static::getAttributeName($attribute);
1374 4
            foreach ($model->getActiveValidators($attrName) as $validator) {
1375 4
                if ($validator instanceof StringValidator && $validator->max !== null) {
1376 4
                    $options['maxlength'] = $validator->max;
1377 4
                    break;
1378
                }
1379
            }
1380
        }
1381 34
    }
1382
1383
    /**
1384
     * Generates a text input tag for the given model attribute.
1385
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1386
     * unless they are explicitly specified in `$options`.
1387
     * @param Model $model the model object
1388
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1389
     * about attribute expression.
1390
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1391
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1392
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1393
     * The following special options are recognized:
1394
     *
1395
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1396
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1397
     *   This is available since version 2.0.3.
1398
     * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
1399
     *   as a placeholder (this behavior is available since version 2.0.14).
1400
     *
1401
     * @return string the generated input tag
1402
     */
1403 17
    public static function activeTextInput($model, $attribute, $options = [])
1404
    {
1405 17
        return static::activeInput('text', $model, $attribute, $options);
1406
    }
1407
1408
    /**
1409
     * Generate placeholder from model attribute label.
1410
     *
1411
     * @param Model $model the model object
1412
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1413
     * about attribute expression.
1414
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1415
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1416
     * @since 2.0.14
1417
     */
1418 33
    protected static function setActivePlaceholder($model, $attribute, &$options = [])
1419
    {
1420 33
        if (isset($options['placeholder']) && $options['placeholder'] === true) {
1421 2
            $attribute = static::getAttributeName($attribute);
1422 2
            $options['placeholder'] = $model->getAttributeLabel($attribute);
1423
        }
1424 33
    }
1425
1426
    /**
1427
     * Generates a hidden input tag for the given model attribute.
1428
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1429
     * unless they are explicitly specified in `$options`.
1430
     * @param Model $model the model object
1431
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1432
     * about attribute expression.
1433
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1434
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1435
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1436
     * @return string the generated input tag
1437
     */
1438 5
    public static function activeHiddenInput($model, $attribute, $options = [])
1439
    {
1440 5
        return static::activeInput('hidden', $model, $attribute, $options);
1441
    }
1442
1443
    /**
1444
     * Generates a password input tag for the given model attribute.
1445
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1446
     * unless they are explicitly specified in `$options`.
1447
     * @param Model $model the model object
1448
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1449
     * about attribute expression.
1450
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1451
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1452
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1453
     * The following special options are recognized:
1454
     *
1455
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1456
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1457
     *   This option is available since version 2.0.6.
1458
     * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
1459
     *   as a placeholder (this behavior is available since version 2.0.14).
1460
     *
1461
     * @return string the generated input tag
1462
     */
1463 3
    public static function activePasswordInput($model, $attribute, $options = [])
1464
    {
1465 3
        return static::activeInput('password', $model, $attribute, $options);
1466
    }
1467
1468
    /**
1469
     * Generates a file input tag for the given model attribute.
1470
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1471
     * unless they are explicitly specified in `$options`.
1472
     * Additionally, if a separate set of HTML options array is defined inside `$options` with a key named `hiddenOptions`,
1473
     * it will be passed to the `activeHiddenInput` field as its own `$options` parameter.
1474
     * @param Model $model the model object
1475
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1476
     * about attribute expression.
1477
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1478
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1479
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1480
     * If `hiddenOptions` parameter which is another set of HTML options array is defined, it will be extracted
1481
     * from `$options` to be used for the hidden input.
1482
     * @return string the generated input tag
1483
     */
1484 2
    public static function activeFileInput($model, $attribute, $options = [])
1485
    {
1486 2
        $hiddenOptions = ['id' => null, 'value' => ''];
1487 2
        if (isset($options['name'])) {
1488 1
            $hiddenOptions['name'] = $options['name'];
1489
        }
1490
        // make sure disabled input is not sending any value
1491 2
        if (!empty($options['disabled'])) {
1492 1
            $hiddenOptions['disabled'] = $options['disabled'];
1493
        }
1494 2
        $hiddenOptions = ArrayHelper::merge($hiddenOptions, ArrayHelper::remove($options, 'hiddenOptions', []));
1495
        // Add a hidden field so that if a model only has a file field, we can
1496
        // still use isset($_POST[$modelClass]) to detect if the input is submitted.
1497
        // The hidden input will be assigned its own set of html options via `$hiddenOptions`.
1498
        // This provides the possibility to interact with the hidden field via client script.
1499
        // Note: For file-field-only model with `disabled` option set to `true` input submitting detection won't work.
1500
1501 2
        return static::activeHiddenInput($model, $attribute, $hiddenOptions)
1502 2
            . static::activeInput('file', $model, $attribute, $options);
1503
    }
1504
1505
    /**
1506
     * Generates a textarea tag for the given model attribute.
1507
     * The model attribute value will be used as the content in the textarea.
1508
     * @param Model $model the model object
1509
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1510
     * about attribute expression.
1511
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1512
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1513
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1514
     * The following special options are recognized:
1515
     *
1516
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1517
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1518
     *   This option is available since version 2.0.6.
1519
     * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
1520
     *   as a placeholder (this behavior is available since version 2.0.14).
1521
     *
1522
     * @return string the generated textarea tag
1523
     */
1524 4
    public static function activeTextarea($model, $attribute, $options = [])
1525
    {
1526 4
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1527 4
        if (isset($options['value'])) {
1528 1
            $value = $options['value'];
1529 1
            unset($options['value']);
1530
        } else {
1531 3
            $value = static::getAttributeValue($model, $attribute);
1532
        }
1533 4
        if (!array_key_exists('id', $options)) {
1534 4
            $options['id'] = static::getInputId($model, $attribute);
1535
        }
1536 4
        self::normalizeMaxLength($model, $attribute, $options);
1537 4
        static::setActivePlaceholder($model, $attribute, $options);
1538 4
        return static::textarea($name, $value, $options);
1539
    }
1540
1541
    /**
1542
     * Generates a radio button tag together with a label for the given model attribute.
1543
     * This method will generate the "checked" tag attribute according to the model attribute value.
1544
     * @param Model $model the model object
1545
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1546
     * about attribute expression.
1547
     * @param array $options the tag options in terms of name-value pairs.
1548
     * See [[booleanInput()]] for details about accepted attributes.
1549
     *
1550
     * @return string the generated radio button tag
1551
     */
1552 4
    public static function activeRadio($model, $attribute, $options = [])
1553
    {
1554 4
        return static::activeBooleanInput('radio', $model, $attribute, $options);
1555
    }
1556
1557
    /**
1558
     * Generates a checkbox tag together with a label for the given model attribute.
1559
     * This method will generate the "checked" tag attribute according to the model attribute value.
1560
     * @param Model $model the model object
1561
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1562
     * about attribute expression.
1563
     * @param array $options the tag options in terms of name-value pairs.
1564
     * See [[booleanInput()]] for details about accepted attributes.
1565
     *
1566
     * @return string the generated checkbox tag
1567
     */
1568 4
    public static function activeCheckbox($model, $attribute, $options = [])
1569
    {
1570 4
        return static::activeBooleanInput('checkbox', $model, $attribute, $options);
1571
    }
1572
1573
    /**
1574
     * Generates a boolean input
1575
     * This method is mainly called by [[activeCheckbox()]] and [[activeRadio()]].
1576
     * @param string $type the input type. This can be either `radio` or `checkbox`.
1577
     * @param Model $model the model object
1578
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1579
     * about attribute expression.
1580
     * @param array $options the tag options in terms of name-value pairs.
1581
     * See [[booleanInput()]] for details about accepted attributes.
1582
     * @return string the generated input element
1583
     * @since 2.0.9
1584
     */
1585 8
    protected static function activeBooleanInput($type, $model, $attribute, $options = [])
1586
    {
1587 8
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1588 8
        $value = static::getAttributeValue($model, $attribute);
1589
1590 8
        if (!array_key_exists('value', $options)) {
1591 8
            $options['value'] = '1';
1592
        }
1593 8
        if (!array_key_exists('uncheck', $options)) {
1594 4
            $options['uncheck'] = '0';
1595 4
        } elseif ($options['uncheck'] === false) {
1596 4
            unset($options['uncheck']);
1597
        }
1598 8
        if (!array_key_exists('label', $options)) {
1599 4
            $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
1600 4
        } elseif ($options['label'] === false) {
1601 4
            unset($options['label']);
1602
        }
1603
1604 8
        $checked = "$value" === "{$options['value']}";
1605
1606 8
        if (!array_key_exists('id', $options)) {
1607 8
            $options['id'] = static::getInputId($model, $attribute);
1608
        }
1609
1610 8
        return static::$type($name, $checked, $options);
1611
    }
1612
1613
    /**
1614
     * Generates a drop-down list for the given model attribute.
1615
     * The selection of the drop-down list is taken from the value of the model attribute.
1616
     * @param Model $model the model object
1617
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1618
     * about attribute expression.
1619
     * @param array $items the option data items. The array keys are option values, and the array values
1620
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1621
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1622
     * If you have a list of data models, you may convert them into the format described above using
1623
     * [[\yii\helpers\ArrayHelper::map()]].
1624
     *
1625
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1626
     * the labels will also be HTML-encoded.
1627
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1628
     *
1629
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1630
     *   to override the value and to set other tag attributes:
1631
     *
1632
     *   ```php
1633
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1634
     *   ```
1635
     *
1636
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1637
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1638
     *
1639
     *   ```php
1640
     *   [
1641
     *       'value1' => ['disabled' => true],
1642
     *       'value2' => ['label' => 'value 2'],
1643
     *   ];
1644
     *   ```
1645
     *
1646
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1647
     *   except that the array keys represent the optgroup labels specified in $items.
1648
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1649
     *   Defaults to false.
1650
     * - encode: bool, whether to encode option prompt and option value characters.
1651
     *   Defaults to `true`. This option is available since 2.0.3.
1652
     *
1653
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1654
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1655
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1656
     *
1657
     * @return string the generated drop-down list tag
1658
     */
1659 3
    public static function activeDropDownList($model, $attribute, $items, $options = [])
1660
    {
1661 3
        if (empty($options['multiple'])) {
1662 2
            return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
1663
        }
1664
1665 1
        return static::activeListBox($model, $attribute, $items, $options);
1666
    }
1667
1668
    /**
1669
     * Generates a list box.
1670
     * The selection of the list box is taken from the value of the model attribute.
1671
     * @param Model $model the model object
1672
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1673
     * about attribute expression.
1674
     * @param array $items the option data items. The array keys are option values, and the array values
1675
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1676
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1677
     * If you have a list of data models, you may convert them into the format described above using
1678
     * [[\yii\helpers\ArrayHelper::map()]].
1679
     *
1680
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1681
     * the labels will also be HTML-encoded.
1682
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1683
     *
1684
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1685
     *   to override the value and to set other tag attributes:
1686
     *
1687
     *   ```php
1688
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1689
     *   ```
1690
     *
1691
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1692
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1693
     *
1694
     *   ```php
1695
     *   [
1696
     *       'value1' => ['disabled' => true],
1697
     *       'value2' => ['label' => 'value 2'],
1698
     *   ];
1699
     *   ```
1700
     *
1701
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1702
     *   except that the array keys represent the optgroup labels specified in $items.
1703
     * - unselect: string, the value that will be submitted when no option is selected.
1704
     *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
1705
     *   mode, we can still obtain the posted unselect value.
1706
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1707
     *   Defaults to false.
1708
     * - encode: bool, whether to encode option prompt and option value characters.
1709
     *   Defaults to `true`. This option is available since 2.0.3.
1710
     *
1711
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1712
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1713
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1714
     *
1715
     * @return string the generated list box tag
1716
     */
1717 3
    public static function activeListBox($model, $attribute, $items, $options = [])
1718
    {
1719 3
        return static::activeListInput('listBox', $model, $attribute, $items, $options);
1720
    }
1721
1722
    /**
1723
     * Generates a list of checkboxes.
1724
     * A checkbox list allows multiple selection, like [[listBox()]].
1725
     * As a result, the corresponding submitted value is an array.
1726
     * The selection of the checkbox list is taken from the value of the model attribute.
1727
     * @param Model $model the model object
1728
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1729
     * about attribute expression.
1730
     * @param array $items the data item used to generate the checkboxes.
1731
     * The array keys are the checkbox values, and the array values are the corresponding labels.
1732
     * Note that the labels will NOT be HTML-encoded, while the values will.
1733
     * @param array $options options (name => config) for the checkbox list container tag.
1734
     * The following options are specially handled:
1735
     *
1736
     * - tag: string|false, the tag name of the container element. False to render checkbox without container.
1737
     *   See also [[tag()]].
1738
     * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
1739
     *   You may set this option to be null to prevent default value submission.
1740
     *   If this option is not set, an empty string will be submitted.
1741
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1742
     *   This option is ignored if `item` option is set.
1743
     * - separator: string, the HTML code that separates items.
1744
     * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
1745
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1746
     *   corresponding to a single item in $items. The signature of this callback must be:
1747
     *
1748
     *   ```php
1749
     *   function ($index, $label, $name, $checked, $value)
1750
     *   ```
1751
     *
1752
     *   where $index is the zero-based index of the checkbox in the whole list; $label
1753
     *   is the label for the checkbox; and $name, $value and $checked represent the name,
1754
     *   value and the checked status of the checkbox input.
1755
     *
1756
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1757
     *
1758
     * @return string the generated checkbox list
1759
     */
1760 1
    public static function activeCheckboxList($model, $attribute, $items, $options = [])
1761
    {
1762 1
        return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
1763
    }
1764
1765
    /**
1766
     * Generates a list of radio buttons.
1767
     * A radio button list is like a checkbox list, except that it only allows single selection.
1768
     * The selection of the radio buttons is taken from the value of the model attribute.
1769
     * @param Model $model the model object
1770
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1771
     * about attribute expression.
1772
     * @param array $items the data item used to generate the radio buttons.
1773
     * The array keys are the radio values, and the array values are the corresponding labels.
1774
     * Note that the labels will NOT be HTML-encoded, while the values will.
1775
     * @param array $options options (name => config) for the radio button list container tag.
1776
     * The following options are specially handled:
1777
     *
1778
     * - tag: string|false, the tag name of the container element. False to render radio button without container.
1779
     *   See also [[tag()]].
1780
     * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
1781
     *   You may set this option to be null to prevent default value submission.
1782
     *   If this option is not set, an empty string will be submitted.
1783
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1784
     *   This option is ignored if `item` option is set.
1785
     * - separator: string, the HTML code that separates items.
1786
     * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
1787
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1788
     *   corresponding to a single item in $items. The signature of this callback must be:
1789
     *
1790
     *   ```php
1791
     *   function ($index, $label, $name, $checked, $value)
1792
     *   ```
1793
     *
1794
     *   where $index is the zero-based index of the radio button in the whole list; $label
1795
     *   is the label for the radio button; and $name, $value and $checked represent the name,
1796
     *   value and the checked status of the radio button input.
1797
     *
1798
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1799
     *
1800
     * @return string the generated radio button list
1801
     */
1802 2
    public static function activeRadioList($model, $attribute, $items, $options = [])
1803
    {
1804 2
        return static::activeListInput('radioList', $model, $attribute, $items, $options);
1805
    }
1806
1807
    /**
1808
     * Generates a list of input fields.
1809
     * This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckboxList()]].
1810
     * @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'.
1811
     * @param Model $model the model object
1812
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1813
     * about attribute expression.
1814
     * @param array $items the data item used to generate the input fields.
1815
     * The array keys are the input values, and the array values are the corresponding labels.
1816
     * Note that the labels will NOT be HTML-encoded, while the values will.
1817
     * @param array $options options (name => config) for the input list. The supported special options
1818
     * depend on the input type specified by `$type`.
1819
     * @return string the generated input list
1820
     */
1821 8
    protected static function activeListInput($type, $model, $attribute, $items, $options = [])
1822
    {
1823 8
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1824 8
        $selection = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1825 8
        if (!array_key_exists('unselect', $options)) {
1826 8
            $options['unselect'] = '';
1827
        }
1828 8
        if (!array_key_exists('id', $options)) {
1829 6
            $options['id'] = static::getInputId($model, $attribute);
1830
        }
1831
1832 8
        return static::$type($name, $selection, $items, $options);
1833
    }
1834
1835
    /**
1836
     * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
1837
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
1838
     * @param array $items the option data items. The array keys are option values, and the array values
1839
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1840
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1841
     * If you have a list of data models, you may convert them into the format described above using
1842
     * [[\yii\helpers\ArrayHelper::map()]].
1843
     *
1844
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1845
     * the labels will also be HTML-encoded.
1846
     * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
1847
     * This method will take out these elements, if any: "prompt", "options" and "groups". See more details
1848
     * in [[dropDownList()]] for the explanation of these elements.
1849
     *
1850
     * @return string the generated list options
1851
     */
1852 8
    public static function renderSelectOptions($selection, $items, &$tagOptions = [])
1853
    {
1854 8
        if (ArrayHelper::isTraversable($selection)) {
1855 3
            $selection = array_map('strval', (array)$selection);
1856
        }
1857
1858 8
        $lines = [];
1859 8
        $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
1860 8
        $encode = ArrayHelper::remove($tagOptions, 'encode', true);
1861 8
        if (isset($tagOptions['prompt'])) {
1862 3
            $promptOptions = ['value' => ''];
1863 3
            if (is_string($tagOptions['prompt'])) {
1864 3
                $promptText = $tagOptions['prompt'];
1865
            } else {
1866 1
                $promptText = $tagOptions['prompt']['text'];
1867 1
                $promptOptions = array_merge($promptOptions, $tagOptions['prompt']['options']);
1868
            }
1869 3
            $promptText = $encode ? static::encode($promptText) : $promptText;
1870 3
            if ($encodeSpaces) {
1871 1
                $promptText = str_replace(' ', '&nbsp;', $promptText);
1872
            }
1873 3
            $lines[] = static::tag('option', $promptText, $promptOptions);
1874
        }
1875
1876 8
        $options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
1877 8
        $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
1878 8
        unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
1879 8
        $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
1880 8
        $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
1881
1882 8
        foreach ($items as $key => $value) {
1883 7
            if (is_array($value)) {
1884 1
                $groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
1885 1
                if (!isset($groupAttrs['label'])) {
1886 1
                    $groupAttrs['label'] = $key;
1887
                }
1888 1
                $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
1889 1
                $content = static::renderSelectOptions($selection, $value, $attrs);
1890 1
                $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
1891
            } else {
1892 7
                $attrs = isset($options[$key]) ? $options[$key] : [];
1893 7
                $attrs['value'] = (string) $key;
1894 7
                if (!array_key_exists('selected', $attrs)) {
1895 7
                    $attrs['selected'] = $selection !== null &&
1896 5
                        (!ArrayHelper::isTraversable($selection) && !strcmp($key, $selection)
1897 5
                        || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn((string)$key, $selection));
0 ignored issues
show
Bug introduced by
It seems like $selection defined by parameter $selection on line 1852 can also be of type string; however, yii\helpers\BaseArrayHelper::isIn() does only seem to accept array|object<Traversable>, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
1898
                }
1899 7
                $text = $encode ? static::encode($value) : $value;
1900 7
                if ($encodeSpaces) {
1901 2
                    $text = str_replace(' ', '&nbsp;', $text);
1902
                }
1903 7
                $lines[] = static::tag('option', $text, $attrs);
1904
            }
1905
        }
1906
1907 8
        return implode("\n", $lines);
1908
    }
1909
1910
    /**
1911
     * Renders the HTML tag attributes.
1912
     *
1913
     * Attributes whose values are of boolean type will be treated as
1914
     * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
1915
     *
1916
     * Attributes whose values are null will not be rendered.
1917
     *
1918
     * The values of attributes will be HTML-encoded using [[encode()]].
1919
     *
1920
     * The "data" attribute is specially handled when it is receiving an array value. In this case,
1921
     * the array will be "expanded" and a list data attributes will be rendered. For example,
1922
     * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered:
1923
     * `data-id="1" data-name="yii"`.
1924
     * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as:
1925
     * `data-params='{"id":1,"name":"yii"}' data-status="ok"`.
1926
     *
1927
     * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
1928
     * @return string the rendering result. If the attributes are not empty, they will be rendered
1929
     * into a string with a leading white space (so that it can be directly appended to the tag name
1930
     * in a tag. If there is no attribute, an empty string will be returned.
1931
     * @see addCssClass()
1932
     */
1933 221
    public static function renderTagAttributes($attributes)
1934
    {
1935 221
        if (count($attributes) > 1) {
1936 168
            $sorted = [];
1937 168
            foreach (static::$attributeOrder as $name) {
1938 168
                if (isset($attributes[$name])) {
1939 168
                    $sorted[$name] = $attributes[$name];
1940
                }
1941
            }
1942 168
            $attributes = array_merge($sorted, $attributes);
1943
        }
1944
1945 221
        $html = '';
1946 221
        foreach ($attributes as $name => $value) {
1947 210
            if (is_bool($value)) {
1948 37
                if ($value) {
1949 37
                    $html .= " $name";
1950
                }
1951 210
            } elseif (is_array($value)) {
1952 10
                if (in_array($name, static::$dataAttributes)) {
1953 3
                    foreach ($value as $n => $v) {
1954 3
                        if (is_array($v)) {
1955 1
                            $html .= " $name-$n='" . Json::htmlEncode($v) . "'";
1956
                        } else {
1957 3
                            $html .= " $name-$n=\"" . static::encode($v) . '"';
1958
                        }
1959
                    }
1960 9
                } elseif ($name === 'class') {
1961 8
                    if (empty($value)) {
1962 8
                        continue;
1963
                    }
1964 3
                    $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
1965 2
                } elseif ($name === 'style') {
1966 1
                    if (empty($value)) {
1967 1
                        continue;
1968
                    }
1969 1
                    $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
1970
                } else {
1971 5
                    $html .= " $name='" . Json::htmlEncode($value) . "'";
1972
                }
1973 204
            } elseif ($value !== null) {
1974 206
                $html .= " $name=\"" . static::encode($value) . '"';
1975
            }
1976
        }
1977
1978 221
        return $html;
1979
    }
1980
1981
    /**
1982
     * Adds a CSS class (or several classes) to the specified options.
1983
     *
1984
     * If the CSS class is already in the options, it will not be added again.
1985
     * If class specification at given options is an array, and some class placed there with the named (string) key,
1986
     * overriding of such key will have no effect. For example:
1987
     *
1988
     * ```php
1989
     * $options = ['class' => ['persistent' => 'initial']];
1990
     * Html::addCssClass($options, ['persistent' => 'override']);
1991
     * var_dump($options['class']); // outputs: array('persistent' => 'initial');
1992
     * ```
1993
     *
1994
     * @param array $options the options to be modified.
1995
     * @param string|array $class the CSS class(es) to be added
1996
     * @see mergeCssClasses()
1997
     * @see removeCssClass()
1998
     */
1999 21
    public static function addCssClass(&$options, $class)
2000
    {
2001 21
        if (isset($options['class'])) {
2002 13
            if (is_array($options['class'])) {
2003 3
                $options['class'] = self::mergeCssClasses($options['class'], (array) $class);
2004
            } else {
2005 11
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
2006 13
                $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
2007
            }
2008
        } else {
2009 14
            $options['class'] = $class;
2010
        }
2011 21
    }
2012
2013
    /**
2014
     * Merges already existing CSS classes with new one.
2015
     * This method provides the priority for named existing classes over additional.
2016
     * @param array $existingClasses already existing CSS classes.
2017
     * @param array $additionalClasses CSS classes to be added.
2018
     * @return array merge result.
2019
     * @see addCssClass()
2020
     */
2021 13
    private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
2022
    {
2023 13
        foreach ($additionalClasses as $key => $class) {
2024 13
            if (is_int($key) && !in_array($class, $existingClasses)) {
2025 12
                $existingClasses[] = $class;
2026 2
            } elseif (!isset($existingClasses[$key])) {
2027 13
                $existingClasses[$key] = $class;
2028
            }
2029
        }
2030
2031 13
        return array_unique($existingClasses);
2032
    }
2033
2034
    /**
2035
     * Removes a CSS class from the specified options.
2036
     * @param array $options the options to be modified.
2037
     * @param string|array $class the CSS class(es) to be removed
2038
     * @see addCssClass()
2039
     */
2040 1
    public static function removeCssClass(&$options, $class)
2041
    {
2042 1
        if (isset($options['class'])) {
2043 1
            if (is_array($options['class'])) {
2044 1
                $classes = array_diff($options['class'], (array) $class);
2045 1
                if (empty($classes)) {
2046 1
                    unset($options['class']);
2047
                } else {
2048 1
                    $options['class'] = $classes;
2049
                }
2050
            } else {
2051 1
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
2052 1
                $classes = array_diff($classes, (array) $class);
2053 1
                if (empty($classes)) {
2054 1
                    unset($options['class']);
2055
                } else {
2056 1
                    $options['class'] = implode(' ', $classes);
2057
                }
2058
            }
2059
        }
2060 1
    }
2061
2062
    /**
2063
     * Adds the specified CSS style to the HTML options.
2064
     *
2065
     * If the options already contain a `style` element, the new style will be merged
2066
     * with the existing one. If a CSS property exists in both the new and the old styles,
2067
     * the old one may be overwritten if `$overwrite` is true.
2068
     *
2069
     * For example,
2070
     *
2071
     * ```php
2072
     * Html::addCssStyle($options, 'width: 100px; height: 200px');
2073
     * ```
2074
     *
2075
     * @param array $options the HTML options to be modified.
2076
     * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
2077
     * array (e.g. `['width' => '100px', 'height' => '200px']`).
2078
     * @param bool $overwrite whether to overwrite existing CSS properties if the new style
2079
     * contain them too.
2080
     * @see removeCssStyle()
2081
     * @see cssStyleFromArray()
2082
     * @see cssStyleToArray()
2083
     */
2084 1
    public static function addCssStyle(&$options, $style, $overwrite = true)
2085
    {
2086 1
        if (!empty($options['style'])) {
2087 1
            $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
2088 1
            $newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
2089 1
            if (!$overwrite) {
2090 1
                foreach ($newStyle as $property => $value) {
2091 1
                    if (isset($oldStyle[$property])) {
2092 1
                        unset($newStyle[$property]);
2093
                    }
2094
                }
2095
            }
2096 1
            $style = array_merge($oldStyle, $newStyle);
2097
        }
2098 1
        $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
2099 1
    }
2100
2101
    /**
2102
     * Removes the specified CSS style from the HTML options.
2103
     *
2104
     * For example,
2105
     *
2106
     * ```php
2107
     * Html::removeCssStyle($options, ['width', 'height']);
2108
     * ```
2109
     *
2110
     * @param array $options the HTML options to be modified.
2111
     * @param string|array $properties the CSS properties to be removed. You may use a string
2112
     * if you are removing a single property.
2113
     * @see addCssStyle()
2114
     */
2115 1
    public static function removeCssStyle(&$options, $properties)
2116
    {
2117 1
        if (!empty($options['style'])) {
2118 1
            $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
2119 1
            foreach ((array) $properties as $property) {
2120 1
                unset($style[$property]);
2121
            }
2122 1
            $options['style'] = static::cssStyleFromArray($style);
2123
        }
2124 1
    }
2125
2126
    /**
2127
     * Converts a CSS style array into a string representation.
2128
     *
2129
     * For example,
2130
     *
2131
     * ```php
2132
     * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
2133
     * // will display: 'width: 100px; height: 200px;'
2134
     * ```
2135
     *
2136
     * @param array $style the CSS style array. The array keys are the CSS property names,
2137
     * and the array values are the corresponding CSS property values.
2138
     * @return string the CSS style string. If the CSS style is empty, a null will be returned.
2139
     */
2140 4
    public static function cssStyleFromArray(array $style)
2141
    {
2142 4
        $result = '';
2143 4
        foreach ($style as $name => $value) {
2144 4
            $result .= "$name: $value; ";
2145
        }
2146
        // return null if empty to avoid rendering the "style" attribute
2147 4
        return $result === '' ? null : rtrim($result);
2148
    }
2149
2150
    /**
2151
     * Converts a CSS style string into an array representation.
2152
     *
2153
     * The array keys are the CSS property names, and the array values
2154
     * are the corresponding CSS property values.
2155
     *
2156
     * For example,
2157
     *
2158
     * ```php
2159
     * print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
2160
     * // will display: ['width' => '100px', 'height' => '200px']
2161
     * ```
2162
     *
2163
     * @param string $style the CSS style string
2164
     * @return array the array representation of the CSS style
2165
     */
2166 3
    public static function cssStyleToArray($style)
2167
    {
2168 3
        $result = [];
2169 3
        foreach (explode(';', $style) as $property) {
2170 3
            $property = explode(':', $property);
2171 3
            if (count($property) > 1) {
2172 3
                $result[trim($property[0])] = trim($property[1]);
2173
            }
2174
        }
2175
2176 3
        return $result;
2177
    }
2178
2179
    /**
2180
     * Returns the real attribute name from the given attribute expression.
2181
     *
2182
     * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
2183
     * It is mainly used in tabular data input and/or input of array type. Below are some examples:
2184
     *
2185
     * - `[0]content` is used in tabular data input to represent the "content" attribute
2186
     *   for the first model in tabular input;
2187
     * - `dates[0]` represents the first array element of the "dates" attribute;
2188
     * - `[0]dates[0]` represents the first array element of the "dates" attribute
2189
     *   for the first model in tabular input.
2190
     *
2191
     * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
2192
     * @param string $attribute the attribute name or expression
2193
     * @return string the attribute name without prefix and suffix.
2194
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2195
     */
2196 56
    public static function getAttributeName($attribute)
2197
    {
2198 56
        if (preg_match(static::$attributeRegex, $attribute, $matches)) {
2199 53
            return $matches[2];
2200
        }
2201
2202 3
        throw new InvalidArgumentException('Attribute name must contain word characters only.');
2203
    }
2204
2205
    /**
2206
     * Returns the value of the specified attribute name or expression.
2207
     *
2208
     * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
2209
     * See [[getAttributeName()]] for more details about attribute expression.
2210
     *
2211
     * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
2212
     * the primary value(s) of the AR instance(s) will be returned instead.
2213
     *
2214
     * @param Model $model the model object
2215
     * @param string $attribute the attribute name or expression
2216
     * @return string|array the corresponding attribute value
2217
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2218
     */
2219 51
    public static function getAttributeValue($model, $attribute)
2220
    {
2221 51
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2222 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2223
        }
2224 50
        $attribute = $matches[2];
2225 50
        $value = $model->$attribute;
2226 50
        if ($matches[3] !== '') {
2227
            foreach (explode('][', trim($matches[3], '[]')) as $id) {
2228
                if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
2229
                    $value = $value[$id];
2230
                } else {
2231
                    return null;
2232
                }
2233
            }
2234
        }
2235
2236
        // https://github.com/yiisoft/yii2/issues/1457
2237 50
        if (is_array($value)) {
2238 1
            foreach ($value as $i => $v) {
2239 1
                if ($v instanceof ActiveRecordInterface) {
2240 1
                    $v = $v->getPrimaryKey(false);
2241 1
                    $value[$i] = is_array($v) ? json_encode($v) : $v;
2242
                }
2243
            }
2244 50
        } elseif ($value instanceof ActiveRecordInterface) {
2245 1
            $value = $value->getPrimaryKey(false);
2246
2247 1
            return is_array($value) ? json_encode($value) : $value;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return is_array($value) ...ncode($value) : $value; (object|integer|double|string|null|boolean) is incompatible with the return type documented by yii\helpers\BaseHtml::getAttributeValue of type string|array.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
2248
        }
2249
2250 50
        return $value;
2251
    }
2252
2253
    /**
2254
     * Generates an appropriate input name for the specified attribute name or expression.
2255
     *
2256
     * This method generates a name that can be used as the input name to collect user input
2257
     * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
2258
     * of the model and the given attribute name. For example, if the form name of the `Post` model
2259
     * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
2260
     *
2261
     * See [[getAttributeName()]] for explanation of attribute expression.
2262
     *
2263
     * @param Model $model the model object
2264
     * @param string $attribute the attribute name or expression
2265
     * @return string the generated input name
2266
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2267
     */
2268 65
    public static function getInputName($model, $attribute)
2269
    {
2270 65
        $formName = $model->formName();
2271 65
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2272 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2273
        }
2274 64
        $prefix = $matches[1];
2275 64
        $attribute = $matches[2];
2276 64
        $suffix = $matches[3];
2277 64
        if ($formName === '' && $prefix === '') {
2278 1
            return $attribute . $suffix;
2279 63
        } elseif ($formName !== '') {
2280 62
            return $formName . $prefix . "[$attribute]" . $suffix;
2281
        }
2282
2283 1
        throw new InvalidArgumentException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
2284
    }
2285
2286
    /**
2287
     * Generates an appropriate input ID for the specified attribute name or expression.
2288
     *
2289
     * This method converts the result [[getInputName()]] into a valid input ID.
2290
     * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
2291
     * @param Model $model the model object
2292
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
2293
     * @return string the generated input ID
2294
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2295
     */
2296 58
    public static function getInputId($model, $attribute)
2297
    {
2298 58
        $name = strtolower(static::getInputName($model, $attribute));
2299 58
        return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
2300
    }
2301
2302
    /**
2303
     * Escapes regular expression to use in JavaScript.
2304
     * @param string $regexp the regular expression to be escaped.
2305
     * @return string the escaped result.
2306
     * @since 2.0.6
2307
     */
2308 1
    public static function escapeJsRegularExpression($regexp)
2309
    {
2310 1
        $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
2311 1
        $deliminator = substr($pattern, 0, 1);
2312 1
        $pos = strrpos($pattern, $deliminator, 1);
2313 1
        $flag = substr($pattern, $pos + 1);
2314 1
        if ($deliminator !== '/') {
2315 1
            $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
2316
        } else {
2317 1
            $pattern = substr($pattern, 0, $pos + 1);
2318
        }
2319 1
        if (!empty($flag)) {
2320 1
            $pattern .= preg_replace('/[^igm]/', '', $flag);
2321
        }
2322
2323 1
        return $pattern;
2324
    }
2325
}
2326