Completed
Push — 2.1 ( d5f162...fcc12f )
by
unknown
49:41 queued 41:18
created

BaseHtml::resetButton()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
ccs 3
cts 3
cp 1
cc 1
eloc 3
nc 1
nop 2
crap 1
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 219
    public static function encode($content, $doubleEncode = true)
110
    {
111 219
        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 206
    public static function tag($name, $content = '', $options = [])
146
    {
147 206
        if ($name === null || $name === false) {
148 3
            return $content;
149
        }
150 205
        $html = '<' .$name . static::renderTagAttributes($options) . '>';
151 205
        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 42
    public static function beginTag($name, $options = [])
166
    {
167 42
        if ($name === null || $name === false) {
168 3
            return '';
169
        }
170
171 42
        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 13
    public static function endTag($name)
182
    {
183 13
        if ($name === null || $name === false) {
184 3
            return '';
185
        }
186
187 12
        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 1
    public static function script($content, $options = [])
214
    {
215 1
        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 40
    public static function beginForm($action = '', $method = 'post', $options = [])
331
    {
332 40
        $action = Url::to($action);
333
334 40
        $hiddenInputs = [];
335
336 40
        $request = Yii::$app->getRequest();
337 40
        if ($request instanceof Request) {
338 37
            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 37
            $csrf = ArrayHelper::remove($options, 'csrf', true);
344
345 37
            if ($csrf && $request->enableCsrfValidation && strcasecmp($method, 'post') === 0) {
346 30
                $hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken());
347
            }
348
        }
349
350 40
        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 40
        $options['action'] = $action;
367 40
        $options['method'] = $method;
368 40
        $form = static::beginTag('form', $options);
369 40
        if (!empty($hiddenInputs)) {
370 35
            $form .= "\n" . implode("\n", $hiddenInputs);
371
        }
372
373 40
        return $form;
374
    }
375
376
    /**
377
     * Generates a form end tag.
378
     * @return string the generated tag
379
     * @see beginForm()
380
     */
381 33
    public static function endForm()
382
    {
383 33
        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 16
    public static function a($text, $url = null, $options = [])
410
    {
411 16
        if ($url !== null) {
412 16
            $options['href'] = Url::to($url);
413
        }
414
415 16
        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 11
    public static function img($src, $options = [])
450
    {
451 11
        $options['src'] = Url::to($src);
452
453 11
        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 11
        if (!isset($options['alt'])) {
462 10
            $options['alt'] = '';
463
        }
464
465 11
        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 22
    public static function label($content, $for = null, $options = [])
482
    {
483 22
        $options['for'] = $for;
484 22
        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 83
    public static function input($type, $name = null, $value = null, $options = [])
557
    {
558 83
        if (!isset($options['type'])) {
559 83
            $options['type'] = $type;
560
        }
561 83
        $options['name'] = $name;
562 83
        $options['value'] = $value === null ? null : (string) $value;
563 83
        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 49
    public static function hiddenInput($name, $value = null, $options = [])
643
    {
644 49
        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 10
    public static function radio($name, $checked = false, $options = [])
712
    {
713 10
        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 9
    public static function checkbox($name, $checked = false, $options = [])
726
    {
727 9
        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 19
    protected static function booleanInput($type, $name, $checked = false, $options = [])
753
    {
754 19
        $options['checked'] = (bool) $checked;
755 19
        $value = array_key_exists('value', $options) ? $options['value'] : '1';
756 19
        if (isset($options['uncheck'])) {
757
            // add a hidden field so that if the checkbox is not selected, it still submits a value
758 6
            $hiddenOptions = [];
759 6
            if (isset($options['form'])) {
760 1
                $hiddenOptions['form'] = $options['form'];
761
            }
762 6
            $hidden = static::hiddenInput($name, $options['uncheck'], $hiddenOptions);
0 ignored issues
show
Documentation introduced by
$options['uncheck'] is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
763 6
            unset($options['uncheck']);
764
        } else {
765 15
            $hidden = '';
766
        }
767 19
        if (isset($options['label'])) {
768 10
            $label = $options['label'];
769 10
            $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
770 10
            unset($options['label'], $options['labelOptions']);
771 10
            $content = static::label(static::input($type, $name, $value, $options) . ' ' . $label, null, $labelOptions);
0 ignored issues
show
Bug introduced by
It seems like $labelOptions defined by isset($options['labelOpt...abelOptions'] : array() on line 769 can also be of type boolean; however, yii\helpers\BaseHtml::label() does only seem to accept array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
772 10
            return $hidden . $content;
773
        }
774
775 13
        return $hidden . static::input($type, $name, $value, $options);
776
    }
777
778
    /**
779
     * Generates a drop-down list.
780
     * @param string $name the input name
781
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
782
     * @param array $items the option data items. The array keys are option values, and the array values
783
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
784
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
785
     * If you have a list of data models, you may convert them into the format described above using
786
     * [[\yii\helpers\ArrayHelper::map()]].
787
     *
788
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
789
     * the labels will also be HTML-encoded.
790
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
791
     *
792
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
793
     *   to override the value and to set other tag attributes:
794
     *
795
     *   ```php
796
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
797
     *   ```
798
     *
799
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
800
     *   and the array values are the extra attributes for the corresponding option tags. For example,
801
     *
802
     *   ```php
803
     *   [
804
     *       'value1' => ['disabled' => true],
805
     *       'value2' => ['label' => 'value 2'],
806
     *   ];
807
     *   ```
808
     *
809
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
810
     *   except that the array keys represent the optgroup labels specified in $items.
811
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
812
     *   Defaults to false.
813
     * - encode: bool, whether to encode option prompt and option value characters.
814
     *   Defaults to `true`. This option is available since 2.0.3.
815
     *
816
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
817
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
818
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
819
     *
820
     * @return string the generated drop-down list tag
821
     */
822 3
    public static function dropDownList($name, $selection = null, $items = [], $options = [])
823
    {
824 3
        if (!empty($options['multiple'])) {
825 1
            return static::listBox($name, $selection, $items, $options);
826
        }
827 3
        $options['name'] = $name;
828 3
        unset($options['unselect']);
829 3
        $selectOptions = static::renderSelectOptions($selection, $items, $options);
830 3
        return static::tag('select', "\n" . $selectOptions . "\n", $options);
831
    }
832
833
    /**
834
     * Generates a list box.
835
     * @param string $name the input name
836
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
837
     * @param array $items the option data items. The array keys are option values, and the array values
838
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
839
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
840
     * If you have a list of data models, you may convert them into the format described above using
841
     * [[\yii\helpers\ArrayHelper::map()]].
842
     *
843
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
844
     * the labels will also be HTML-encoded.
845
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
846
     *
847
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
848
     *   to override the value and to set other tag attributes:
849
     *
850
     *   ```php
851
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
852
     *   ```
853
     *
854
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
855
     *   and the array values are the extra attributes for the corresponding option tags. For example,
856
     *
857
     *   ```php
858
     *   [
859
     *       'value1' => ['disabled' => true],
860
     *       'value2' => ['label' => 'value 2'],
861
     *   ];
862
     *   ```
863
     *
864
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
865
     *   except that the array keys represent the optgroup labels specified in $items.
866
     * - unselect: string, the value that will be submitted when no option is selected.
867
     *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
868
     *   mode, we can still obtain the posted unselect value.
869
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
870
     *   Defaults to false.
871
     * - encode: bool, whether to encode option prompt and option value characters.
872
     *   Defaults to `true`. This option is available since 2.0.3.
873
     *
874
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
875
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
876
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
877
     *
878
     * @return string the generated list box tag
879
     */
880 5
    public static function listBox($name, $selection = null, $items = [], $options = [])
881
    {
882 5
        if (!array_key_exists('size', $options)) {
883 5
            $options['size'] = 4;
884
        }
885 5
        if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) {
886 4
            $name .= '[]';
887
        }
888 5
        $options['name'] = $name;
889 5
        if (isset($options['unselect'])) {
890
            // add a hidden field so that if the list box has no option being selected, it still submits a value
891 4
            if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) {
892 2
                $name = substr($name, 0, -2);
893
            }
894 4
            $hidden = static::hiddenInput($name, $options['unselect']);
895 4
            unset($options['unselect']);
896
        } else {
897 2
            $hidden = '';
898
        }
899 5
        $selectOptions = static::renderSelectOptions($selection, $items, $options);
900 5
        return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
901
    }
902
903
    /**
904
     * Generates a list of checkboxes.
905
     * A checkbox list allows multiple selection, like [[listBox()]].
906
     * As a result, the corresponding submitted value is an array.
907
     * @param string $name the name attribute of each checkbox.
908
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
909
     * @param array $items the data item used to generate the checkboxes.
910
     * The array keys are the checkbox values, while the array values are the corresponding labels.
911
     * @param array $options options (name => config) for the checkbox list container tag.
912
     * The following options are specially handled:
913
     *
914
     * - tag: string|false, the tag name of the container element. False to render checkbox without container.
915
     *   See also [[tag()]].
916
     * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
917
     *   By setting this option, a hidden input will be generated.
918
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
919
     *   This option is ignored if `item` option is set.
920
     * - separator: string, the HTML code that separates items.
921
     * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
922
     * - item: callable, a callback that can be used to customize the generation of the HTML code
923
     *   corresponding to a single item in $items. The signature of this callback must be:
924
     *
925
     *   ```php
926
     *   function ($index, $label, $name, $checked, $value)
927
     *   ```
928
     *
929
     *   where $index is the zero-based index of the checkbox in the whole list; $label
930
     *   is the label for the checkbox; and $name, $value and $checked represent the name,
931
     *   value and the checked status of the checkbox input, respectively.
932
     *
933
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
934
     *
935
     * @return string the generated checkbox list
936
     */
937 2
    public static function checkboxList($name, $selection = null, $items = [], $options = [])
938
    {
939 2
        if (substr($name, -2) !== '[]') {
940 2
            $name .= '[]';
941
        }
942
943 2
        $formatter = ArrayHelper::remove($options, 'item');
944 2
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
945 2
        $encode = ArrayHelper::remove($options, 'encode', true);
946 2
        $separator = ArrayHelper::remove($options, 'separator', "\n");
947 2
        $tag = ArrayHelper::remove($options, 'tag', 'div');
948
949 2
        $lines = [];
950 2
        $index = 0;
951 2
        foreach ($items as $value => $label) {
952 2
            $checked = $selection !== null &&
953 1
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
954 2
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn($value, $selection));
0 ignored issues
show
Bug introduced by
It seems like $selection defined by parameter $selection on line 937 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...
955 2
            if ($formatter !== null) {
956 1
                $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
957
            } else {
958 2
                $lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [
959 2
                    'value' => $value,
960 2
                    'label' => $encode ? static::encode($label) : $label,
961
                ]));
962
            }
963 2
            $index++;
964
        }
965
966 2
        if (isset($options['unselect'])) {
967
            // add a hidden field so that if the list box has no option being selected, it still submits a value
968 2
            $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
969 2
            $hidden = static::hiddenInput($name2, $options['unselect']);
970 2
            unset($options['unselect']);
971
        } else {
972 1
            $hidden = '';
973
        }
974
975 2
        $visibleContent = implode($separator, $lines);
976
977 2
        if ($tag === false) {
978 1
            return $hidden . $visibleContent;
979
        }
980
981 2
        return $hidden . static::tag($tag, $visibleContent, $options);
982
    }
983
984
    /**
985
     * Generates a list of radio buttons.
986
     * A radio button list is like a checkbox list, except that it only allows single selection.
987
     * @param string $name the name attribute of each radio button.
988
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
989
     * @param array $items the data item used to generate the radio buttons.
990
     * The array keys are the radio button values, while the array values are the corresponding labels.
991
     * @param array $options options (name => config) for the radio button list container tag.
992
     * The following options are specially handled:
993
     *
994
     * - tag: string|false, the tag name of the container element. False to render radio buttons without container.
995
     *   See also [[tag()]].
996
     * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
997
     *   By setting this option, a hidden input will be generated.
998
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
999
     *   This option is ignored if `item` option is set.
1000
     * - separator: string, the HTML code that separates items.
1001
     * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
1002
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1003
     *   corresponding to a single item in $items. The signature of this callback must be:
1004
     *
1005
     *   ```php
1006
     *   function ($index, $label, $name, $checked, $value)
1007
     *   ```
1008
     *
1009
     *   where $index is the zero-based index of the radio button in the whole list; $label
1010
     *   is the label for the radio button; and $name, $value and $checked represent the name,
1011
     *   value and the checked status of the radio button input, respectively.
1012
     *
1013
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1014
     *
1015
     * @return string the generated radio button list
1016
     */
1017 2
    public static function radioList($name, $selection = null, $items = [], $options = [])
1018
    {
1019 2
        $formatter = ArrayHelper::remove($options, 'item');
1020 2
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
1021 2
        $encode = ArrayHelper::remove($options, 'encode', true);
1022 2
        $separator = ArrayHelper::remove($options, 'separator', "\n");
1023 2
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1024
        // add a hidden field so that if the list box has no option being selected, it still submits a value
1025 2
        $hidden = isset($options['unselect']) ? static::hiddenInput($name, $options['unselect']) : '';
1026 2
        unset($options['unselect']);
1027
1028 2
        $lines = [];
1029 2
        $index = 0;
1030 2
        foreach ($items as $value => $label) {
1031 2
            $checked = $selection !== null &&
1032 1
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
1033 2
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn($value, $selection));
0 ignored issues
show
Bug introduced by
It seems like $selection defined by parameter $selection on line 1017 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...
1034 2
            if ($formatter !== null) {
1035 1
                $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
1036
            } else {
1037 2
                $lines[] = static::radio($name, $checked, array_merge($itemOptions, [
1038 2
                    'value' => $value,
1039 2
                    'label' => $encode ? static::encode($label) : $label,
1040
                ]));
1041
            }
1042 2
            $index++;
1043
        }
1044 2
        $visibleContent = implode($separator, $lines);
1045
1046 2
        if ($tag === false) {
1047 1
            return $hidden . $visibleContent;
1048
        }
1049
1050 2
        return $hidden . static::tag($tag, $visibleContent, $options);
1051
    }
1052
1053
    /**
1054
     * Generates an unordered list.
1055
     * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
1056
     * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
1057
     * @param array $options options (name => config) for the radio button list. The following options are supported:
1058
     *
1059
     * - encode: boolean, whether to HTML-encode the items. Defaults to true.
1060
     *   This option is ignored if the `item` option is specified.
1061
     * - separator: string, the HTML code that separates items. Defaults to a simple newline (`"\n"`).
1062
     *   This option is available since version 2.0.7.
1063
     * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
1064
     * - item: callable, a callback that is used to generate each individual list item.
1065
     *   The signature of this callback must be:
1066
     *
1067
     *   ```php
1068
     *   function ($item, $index)
1069
     *   ```
1070
     *
1071
     *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
1072
     *   the whole list item tag.
1073
     *
1074
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1075
     *
1076
     * @return string the generated unordered list. An empty list tag will be returned if `$items` is empty.
1077
     */
1078 4
    public static function ul($items, $options = [])
1079
    {
1080 4
        $tag = ArrayHelper::remove($options, 'tag', 'ul');
1081 4
        $encode = ArrayHelper::remove($options, 'encode', true);
1082 4
        $formatter = ArrayHelper::remove($options, 'item');
1083 4
        $separator = ArrayHelper::remove($options, 'separator', "\n");
1084 4
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
1085
1086 4
        if (empty($items)) {
1087 2
            return static::tag($tag, '', $options);
1088
        }
1089
1090 4
        $results = [];
1091 4
        foreach ($items as $index => $item) {
1092 4
            if ($formatter !== null) {
1093 2
                $results[] = call_user_func($formatter, $item, $index);
1094
            } else {
1095 4
                $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
1096
            }
1097
        }
1098
1099 4
        return static::tag(
1100 4
            $tag,
1101 4
            $separator . implode($separator, $results) . $separator,
1102 4
            $options
1103
        );
1104
    }
1105
1106
    /**
1107
     * Generates an ordered list.
1108
     * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
1109
     * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
1110
     * @param array $options options (name => config) for the radio button list. The following options are supported:
1111
     *
1112
     * - encode: boolean, whether to HTML-encode the items. Defaults to true.
1113
     *   This option is ignored if the `item` option is specified.
1114
     * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
1115
     * - item: callable, a callback that is used to generate each individual list item.
1116
     *   The signature of this callback must be:
1117
     *
1118
     *   ```php
1119
     *   function ($item, $index)
1120
     *   ```
1121
     *
1122
     *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
1123
     *   the whole list item tag.
1124
     *
1125
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1126
     *
1127
     * @return string the generated ordered list. An empty string is returned if `$items` is empty.
1128
     */
1129 1
    public static function ol($items, $options = [])
1130
    {
1131 1
        $options['tag'] = 'ol';
1132 1
        return static::ul($items, $options);
1133
    }
1134
1135
    /**
1136
     * Generates a label tag for the given model attribute.
1137
     * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
1138
     * @param Model $model the model object
1139
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1140
     * about attribute expression.
1141
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1142
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1143
     * If a value is null, the corresponding attribute will not be rendered.
1144
     * The following options are specially handled:
1145
     *
1146
     * - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
1147
     *   If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
1148
     *   (after encoding).
1149
     *
1150
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1151
     *
1152
     * @return string the generated label tag
1153
     */
1154 11
    public static function activeLabel($model, $attribute, $options = [])
1155
    {
1156 11
        $for = ArrayHelper::remove($options, 'for', static::getInputId($model, $attribute));
1157 11
        $attribute = static::getAttributeName($attribute);
1158 11
        $label = ArrayHelper::remove($options, 'label', static::encode($model->getAttributeLabel($attribute)));
1159 11
        return static::label($label, $for, $options);
1160
    }
1161
1162
    /**
1163
     * Generates a hint tag for the given model attribute.
1164
     * The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]].
1165
     * If no hint content can be obtained, method will return an empty string.
1166
     * @param Model $model the model object
1167
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1168
     * about attribute expression.
1169
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1170
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1171
     * If a value is null, the corresponding attribute will not be rendered.
1172
     * The following options are specially handled:
1173
     *
1174
     * - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]].
1175
     *   If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display
1176
     *   (without encoding).
1177
     *
1178
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1179
     *
1180
     * @return string the generated hint tag
1181
     * @since 2.0.4
1182
     */
1183 11
    public static function activeHint($model, $attribute, $options = [])
1184
    {
1185 11
        $attribute = static::getAttributeName($attribute);
1186 11
        $hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute);
1187 11
        if (empty($hint)) {
1188 3
            return '';
1189
        }
1190 8
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1191 8
        unset($options['hint']);
1192 8
        return static::tag($tag, $hint, $options);
1193
    }
1194
1195
    /**
1196
     * Generates a summary of the validation errors.
1197
     * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
1198
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
1199
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1200
     *
1201
     * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
1202
     * - footer: string, the footer HTML for the error summary. Defaults to empty string.
1203
     * - encode: boolean, if set to false then the error messages won't be encoded. Defaults to `true`.
1204
     * - showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise
1205
     *   only the first error message for each attribute will be shown. Defaults to `false`.
1206
     *   Option is available since 2.0.10.
1207
     *
1208
     * The rest of the options will be rendered as the attributes of the container tag.
1209
     *
1210
     * @return string the generated error summary
1211
     */
1212 7
    public static function errorSummary($models, $options = [])
1213
    {
1214 7
        $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
1215 7
        $footer = ArrayHelper::remove($options, 'footer', '');
1216 7
        $encode = ArrayHelper::remove($options, 'encode', true);
1217 7
        $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
1218 7
        unset($options['header']);
1219 7
        $lines = self::collectErrors($models, $encode, $showAllErrors);
1220 7
        if (empty($lines)) {
1221
            // still render the placeholder for client-side validation use
1222 2
            $content = '<ul></ul>';
1223 2
            $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
1224
        } else {
1225 5
            $content = '<ul><li>' . implode("</li>\n<li>", $lines) . '</li></ul>';
1226
        }
1227
1228 7
        return Html::tag('div', $header . $content . $footer, $options);
1229
    }
1230
1231
    /**
1232
     * Return array of the validation errors
1233
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
1234
     * @param $encode boolean, if set to false then the error messages won't be encoded.
1235
     * @param $showAllErrors boolean, if set to true every error message for each attribute will be shown otherwise
1236
     * only the first error message for each attribute will be shown.
1237
     * @return array of the validation errors
1238
     * @since 2.0.14
1239
     */
1240 7
    private static function collectErrors($models, $encode, $showAllErrors)
1241
    {
1242 7
        $lines = [];
1243 7
        if (!is_array($models)) {
1244 7
            $models = [$models];
1245
        }
1246
1247 7
        foreach ($models as $model) {
1248 7
            $lines = array_unique(array_merge($lines, $model->getErrorSummary($showAllErrors)));
1249
        }
1250
1251 7
        if ($encode) {
1252 6
            for ($i = 0, $linesCount = count($lines); $i < $linesCount; $i++) {
1253 4
                $lines[$i] = Html::encode($lines[$i]);
1254
            }
1255
        }
1256
1257 7
        return $lines;
1258
    }
1259
1260
    /**
1261
     * Generates a tag that contains the first validation error of the specified model attribute.
1262
     * Note that even if there is no validation error, this method will still return an empty error tag.
1263
     * @param Model $model the model object
1264
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1265
     * about attribute expression.
1266
     * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
1267
     * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1268
     *
1269
     * The following options are specially handled:
1270
     *
1271
     * - tag: this specifies the tag name. If not set, "div" will be used.
1272
     *   See also [[tag()]].
1273
     * - encode: boolean, if set to false then the error message won't be encoded.
1274
     * - errorSource (since 2.0.14): \Closure|callable, callback that will be called to obtain an error message.
1275
     *   The signature of the callback must be: `function ($model, $attribute)` and return a string.
1276
     *   When not set, the `$model->getFirstError()` method will be called.
1277
     *
1278
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1279
     *
1280
     * @return string the generated label tag
1281
     */
1282 10
    public static function error($model, $attribute, $options = [])
1283
    {
1284 10
        $attribute = static::getAttributeName($attribute);
1285 10
        $errorSource = ArrayHelper::remove($options, 'errorSource');
1286 10
        if ($errorSource !== null) {
1287 1
            $error = call_user_func($errorSource, $model, $attribute);
1288
        } else {
1289 10
            $error = $model->getFirstError($attribute);
1290
        }
1291 10
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1292 10
        $encode = ArrayHelper::remove($options, 'encode', true);
1293 10
        return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
1294
    }
1295
1296
    /**
1297
     * Generates an input tag for the given model attribute.
1298
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1299
     * unless they are explicitly specified in `$options`.
1300
     * @param string $type the input type (e.g. 'text', 'password')
1301
     * @param Model $model the model object
1302
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1303
     * about attribute expression.
1304
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1305
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1306
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1307
     * @return string the generated input tag
1308
     */
1309 32
    public static function activeInput($type, $model, $attribute, $options = [])
1310
    {
1311 32
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1312 32
        $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1313 32
        if (!array_key_exists('id', $options)) {
1314 22
            $options['id'] = static::getInputId($model, $attribute);
1315
        }
1316
1317 32
        self::setActivePlaceholder($model, $attribute, $options);
1318
1319 32
        return static::input($type, $name, $value, $options);
1320
    }
1321
1322
    /**
1323
     * If `maxlength` option is set true and the model attribute is validated by a string validator,
1324
     * the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1325
     * @param Model $model the model object
1326
     * @param string $attribute the attribute name or expression.
1327
     * @param array $options the tag options in terms of name-value pairs.
1328
     */
1329 29
    private static function normalizeMaxLength($model, $attribute, &$options)
1330
    {
1331 29
        if (isset($options['maxlength']) && $options['maxlength'] === true) {
1332 3
            unset($options['maxlength']);
1333 3
            $attrName = static::getAttributeName($attribute);
1334 3
            foreach ($model->getActiveValidators($attrName) as $validator) {
1335 3
                if ($validator instanceof StringValidator && $validator->max !== null) {
1336 3
                    $options['maxlength'] = $validator->max;
1337 3
                    break;
1338
                }
1339
            }
1340
        }
1341 29
    }
1342
1343
    /**
1344
     * Generates a text input tag for the given model attribute.
1345
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1346
     * unless they are explicitly specified in `$options`.
1347
     * @param Model $model the model object
1348
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1349
     * about attribute expression.
1350
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1351
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1352
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1353
     * The following special options are recognized:
1354
     *
1355
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1356
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1357
     *   This is available since version 2.0.3.
1358
     * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
1359
     *   as a placeholder (this behavior is available since version 2.0.14).
1360
     *
1361
     * @return string the generated input tag
1362
     */
1363 22
    public static function activeTextInput($model, $attribute, $options = [])
1364
    {
1365 22
        self::normalizeMaxLength($model, $attribute, $options);
1366 22
        return static::activeInput('text', $model, $attribute, $options);
1367
    }
1368
1369
    /**
1370
     * Generate placeholder from model attribute label.
1371
     *
1372
     * @param Model $model the model object
1373
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1374
     * about attribute expression.
1375
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1376
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1377
     * @since 2.0.14
1378
     */
1379 36
    protected static function setActivePlaceholder($model, $attribute, &$options = [])
1380
    {
1381 36
        if (isset($options['placeholder']) && $options['placeholder'] === true) {
1382 1
            $options['placeholder'] = $model->getAttributeLabel($attribute);
1383
        }
1384 36
    }
1385
1386
    /**
1387
     * Generates a hidden input tag for the given model attribute.
1388
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1389
     * unless they are explicitly specified in `$options`.
1390
     * @param Model $model the model object
1391
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1392
     * about attribute expression.
1393
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1394
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1395
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1396
     * @return string the generated input tag
1397
     */
1398 5
    public static function activeHiddenInput($model, $attribute, $options = [])
1399
    {
1400 5
        return static::activeInput('hidden', $model, $attribute, $options);
1401
    }
1402
1403
    /**
1404
     * Generates a password input tag for the given model attribute.
1405
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1406
     * unless they are explicitly specified in `$options`.
1407
     * @param Model $model the model object
1408
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1409
     * about attribute expression.
1410
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1411
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1412
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1413
     * The following special options are recognized:
1414
     *
1415
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1416
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1417
     *   This option is available since version 2.0.6.
1418
     * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
1419
     *   as a placeholder (this behavior is available since version 2.0.14).
1420
     *
1421
     * @return string the generated input tag
1422
     */
1423 3
    public static function activePasswordInput($model, $attribute, $options = [])
1424
    {
1425 3
        self::normalizeMaxLength($model, $attribute, $options);
1426 3
        return static::activeInput('password', $model, $attribute, $options);
1427
    }
1428
1429
    /**
1430
     * Generates a file input tag for the given model attribute.
1431
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1432
     * unless they are explicitly specified in `$options`.
1433
     * @param Model $model the model object
1434
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1435
     * about attribute expression.
1436
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1437
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1438
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1439
     * @return string the generated input tag
1440
     */
1441 2
    public static function activeFileInput($model, $attribute, $options = [])
1442
    {
1443
        // add a hidden field so that if a model only has a file field, we can
1444
        // still use isset($_POST[$modelClass]) to detect if the input is submitted
1445 2
        $hiddenOptions = ['id' => null, 'value' => ''];
1446 2
        if (isset($options['name'])) {
1447 1
            $hiddenOptions['name'] = $options['name'];
1448
        }
1449
1450 2
        return static::activeHiddenInput($model, $attribute, $hiddenOptions)
1451 2
            . static::activeInput('file', $model, $attribute, $options);
1452
    }
1453
1454
    /**
1455
     * Generates a textarea tag for the given model attribute.
1456
     * The model attribute value will be used as the content in the textarea.
1457
     * @param Model $model the model object
1458
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1459
     * about attribute expression.
1460
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1461
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1462
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1463
     * The following special options are recognized:
1464
     *
1465
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1466
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1467
     *   This option is available since version 2.0.6.
1468
     * - placeholder: string|boolean, when `placeholder` equals `true`, the attribute label from the $model will be used
1469
     *   as a placeholder (this behavior is available since version 2.0.14).
1470
     *
1471
     * @return string the generated textarea tag
1472
     */
1473 4
    public static function activeTextarea($model, $attribute, $options = [])
1474
    {
1475 4
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1476 4
        if (isset($options['value'])) {
1477 1
            $value = $options['value'];
1478 1
            unset($options['value']);
1479
        } else {
1480 3
            $value = static::getAttributeValue($model, $attribute);
1481
        }
1482 4
        if (!array_key_exists('id', $options)) {
1483 4
            $options['id'] = static::getInputId($model, $attribute);
1484
        }
1485 4
        self::normalizeMaxLength($model, $attribute, $options);
1486 4
        self::setActivePlaceholder($model, $attribute, $options);
1487 4
        return static::textarea($name, $value, $options);
1488
    }
1489
1490
    /**
1491
     * Generates a radio button tag together with a label for the given model attribute.
1492
     * This method will generate the "checked" tag attribute according to the model attribute value.
1493
     * @param Model $model the model object
1494
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1495
     * about attribute expression.
1496
     * @param array $options the tag options in terms of name-value pairs.
1497
     * See [[booleanInput()]] for details about accepted attributes.
1498
     *
1499
     * @return string the generated radio button tag
1500
     */
1501 4
    public static function activeRadio($model, $attribute, $options = [])
1502
    {
1503 4
        return static::activeBooleanInput('radio', $model, $attribute, $options);
1504
    }
1505
1506
    /**
1507
     * Generates a checkbox tag together with a label for the given model attribute.
1508
     * This method will generate the "checked" tag attribute according to the model attribute value.
1509
     * @param Model $model the model object
1510
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1511
     * about attribute expression.
1512
     * @param array $options the tag options in terms of name-value pairs.
1513
     * See [[booleanInput()]] for details about accepted attributes.
1514
     *
1515
     * @return string the generated checkbox tag
1516
     */
1517 4
    public static function activeCheckbox($model, $attribute, $options = [])
1518
    {
1519 4
        return static::activeBooleanInput('checkbox', $model, $attribute, $options);
1520
    }
1521
1522
    /**
1523
     * Generates a boolean input
1524
     * This method is mainly called by [[activeCheckbox()]] and [[activeRadio()]].
1525
     * @param string $type the input type. This can be either `radio` or `checkbox`.
1526
     * @param Model $model the model object
1527
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1528
     * about attribute expression.
1529
     * @param array $options the tag options in terms of name-value pairs.
1530
     * See [[booleanInput()]] for details about accepted attributes.
1531
     * @return string the generated input element
1532
     * @since 2.0.9
1533
     */
1534 8
    protected static function activeBooleanInput($type, $model, $attribute, $options = [])
1535
    {
1536 8
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1537 8
        $value = static::getAttributeValue($model, $attribute);
1538
1539 8
        if (!array_key_exists('value', $options)) {
1540 8
            $options['value'] = '1';
1541
        }
1542 8
        if (!array_key_exists('uncheck', $options)) {
1543 4
            $options['uncheck'] = '0';
1544 4
        } elseif ($options['uncheck'] === false) {
1545 4
            unset($options['uncheck']);
1546
        }
1547 8
        if (!array_key_exists('label', $options)) {
1548 4
            $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
1549 4
        } elseif ($options['label'] === false) {
1550 4
            unset($options['label']);
1551
        }
1552
1553 8
        $checked = "$value" === "{$options['value']}";
1554
1555 8
        if (!array_key_exists('id', $options)) {
1556 8
            $options['id'] = static::getInputId($model, $attribute);
1557
        }
1558
1559 8
        return static::$type($name, $checked, $options);
1560
    }
1561
1562
    /**
1563
     * Generates a drop-down list for the given model attribute.
1564
     * The selection of the drop-down list is taken from the value of the model attribute.
1565
     * @param Model $model the model object
1566
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1567
     * about attribute expression.
1568
     * @param array $items the option data items. The array keys are option values, and the array values
1569
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1570
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1571
     * If you have a list of data models, you may convert them into the format described above using
1572
     * [[\yii\helpers\ArrayHelper::map()]].
1573
     *
1574
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1575
     * the labels will also be HTML-encoded.
1576
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1577
     *
1578
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1579
     *   to override the value and to set other tag attributes:
1580
     *
1581
     *   ```php
1582
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1583
     *   ```
1584
     *
1585
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1586
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1587
     *
1588
     *   ```php
1589
     *   [
1590
     *       'value1' => ['disabled' => true],
1591
     *       'value2' => ['label' => 'value 2'],
1592
     *   ];
1593
     *   ```
1594
     *
1595
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1596
     *   except that the array keys represent the optgroup labels specified in $items.
1597
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1598
     *   Defaults to false.
1599
     * - encode: bool, whether to encode option prompt and option value characters.
1600
     *   Defaults to `true`. This option is available since 2.0.3.
1601
     *
1602
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1603
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1604
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1605
     *
1606
     * @return string the generated drop-down list tag
1607
     */
1608 3
    public static function activeDropDownList($model, $attribute, $items, $options = [])
1609
    {
1610 3
        if (empty($options['multiple'])) {
1611 2
            return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
1612
        }
1613
1614 1
        return static::activeListBox($model, $attribute, $items, $options);
1615
    }
1616
1617
    /**
1618
     * Generates a list box.
1619
     * The selection of the list box is taken from the value of the model attribute.
1620
     * @param Model $model the model object
1621
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1622
     * about attribute expression.
1623
     * @param array $items the option data items. The array keys are option values, and the array values
1624
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1625
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1626
     * If you have a list of data models, you may convert them into the format described above using
1627
     * [[\yii\helpers\ArrayHelper::map()]].
1628
     *
1629
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1630
     * the labels will also be HTML-encoded.
1631
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1632
     *
1633
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1634
     *   to override the value and to set other tag attributes:
1635
     *
1636
     *   ```php
1637
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1638
     *   ```
1639
     *
1640
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1641
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1642
     *
1643
     *   ```php
1644
     *   [
1645
     *       'value1' => ['disabled' => true],
1646
     *       'value2' => ['label' => 'value 2'],
1647
     *   ];
1648
     *   ```
1649
     *
1650
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1651
     *   except that the array keys represent the optgroup labels specified in $items.
1652
     * - unselect: string, the value that will be submitted when no option is selected.
1653
     *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
1654
     *   mode, we can still obtain the posted unselect value.
1655
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1656
     *   Defaults to false.
1657
     * - encode: bool, whether to encode option prompt and option value characters.
1658
     *   Defaults to `true`. This option is available since 2.0.3.
1659
     *
1660
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1661
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1662
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1663
     *
1664
     * @return string the generated list box tag
1665
     */
1666 3
    public static function activeListBox($model, $attribute, $items, $options = [])
1667
    {
1668 3
        return static::activeListInput('listBox', $model, $attribute, $items, $options);
1669
    }
1670
1671
    /**
1672
     * Generates a list of checkboxes.
1673
     * A checkbox list allows multiple selection, like [[listBox()]].
1674
     * As a result, the corresponding submitted value is an array.
1675
     * The selection of the checkbox list is taken from the value of the model attribute.
1676
     * @param Model $model the model object
1677
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1678
     * about attribute expression.
1679
     * @param array $items the data item used to generate the checkboxes.
1680
     * The array keys are the checkbox values, and the array values are the corresponding labels.
1681
     * Note that the labels will NOT be HTML-encoded, while the values will.
1682
     * @param array $options options (name => config) for the checkbox list container tag.
1683
     * The following options are specially handled:
1684
     *
1685
     * - tag: string|false, the tag name of the container element. False to render checkbox without container.
1686
     *   See also [[tag()]].
1687
     * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
1688
     *   You may set this option to be null to prevent default value submission.
1689
     *   If this option is not set, an empty string will be submitted.
1690
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1691
     *   This option is ignored if `item` option is set.
1692
     * - separator: string, the HTML code that separates items.
1693
     * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
1694
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1695
     *   corresponding to a single item in $items. The signature of this callback must be:
1696
     *
1697
     *   ```php
1698
     *   function ($index, $label, $name, $checked, $value)
1699
     *   ```
1700
     *
1701
     *   where $index is the zero-based index of the checkbox in the whole list; $label
1702
     *   is the label for the checkbox; and $name, $value and $checked represent the name,
1703
     *   value and the checked status of the checkbox input.
1704
     *
1705
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1706
     *
1707
     * @return string the generated checkbox list
1708
     */
1709 1
    public static function activeCheckboxList($model, $attribute, $items, $options = [])
1710
    {
1711 1
        return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
1712
    }
1713
1714
    /**
1715
     * Generates a list of radio buttons.
1716
     * A radio button list is like a checkbox list, except that it only allows single selection.
1717
     * The selection of the radio buttons is taken from the value of the model attribute.
1718
     * @param Model $model the model object
1719
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1720
     * about attribute expression.
1721
     * @param array $items the data item used to generate the radio buttons.
1722
     * The array keys are the radio values, and the array values are the corresponding labels.
1723
     * Note that the labels will NOT be HTML-encoded, while the values will.
1724
     * @param array $options options (name => config) for the radio button list container tag.
1725
     * The following options are specially handled:
1726
     *
1727
     * - tag: string|false, the tag name of the container element. False to render radio button without container.
1728
     *   See also [[tag()]].
1729
     * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
1730
     *   You may set this option to be null to prevent default value submission.
1731
     *   If this option is not set, an empty string will be submitted.
1732
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1733
     *   This option is ignored if `item` option is set.
1734
     * - separator: string, the HTML code that separates items.
1735
     * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
1736
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1737
     *   corresponding to a single item in $items. The signature of this callback must be:
1738
     *
1739
     *   ```php
1740
     *   function ($index, $label, $name, $checked, $value)
1741
     *   ```
1742
     *
1743
     *   where $index is the zero-based index of the radio button in the whole list; $label
1744
     *   is the label for the radio button; and $name, $value and $checked represent the name,
1745
     *   value and the checked status of the radio button input.
1746
     *
1747
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1748
     *
1749
     * @return string the generated radio button list
1750
     */
1751 1
    public static function activeRadioList($model, $attribute, $items, $options = [])
1752
    {
1753 1
        return static::activeListInput('radioList', $model, $attribute, $items, $options);
1754
    }
1755
1756
    /**
1757
     * Generates a list of input fields.
1758
     * This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckboxList()]].
1759
     * @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'.
1760
     * @param Model $model the model object
1761
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1762
     * about attribute expression.
1763
     * @param array $items the data item used to generate the input fields.
1764
     * The array keys are the input values, and the array values are the corresponding labels.
1765
     * Note that the labels will NOT be HTML-encoded, while the values will.
1766
     * @param array $options options (name => config) for the input list. The supported special options
1767
     * depend on the input type specified by `$type`.
1768
     * @return string the generated input list
1769
     */
1770 7
    protected static function activeListInput($type, $model, $attribute, $items, $options = [])
1771
    {
1772 7
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1773 7
        $selection = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1774 7
        if (!array_key_exists('unselect', $options)) {
1775 7
            $options['unselect'] = '';
1776
        }
1777 7
        if (!array_key_exists('id', $options)) {
1778 5
            $options['id'] = static::getInputId($model, $attribute);
1779
        }
1780
1781 7
        return static::$type($name, $selection, $items, $options);
1782
    }
1783
1784
    /**
1785
     * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
1786
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
1787
     * @param array $items the option data items. The array keys are option values, and the array values
1788
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1789
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1790
     * If you have a list of data models, you may convert them into the format described above using
1791
     * [[\yii\helpers\ArrayHelper::map()]].
1792
     *
1793
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1794
     * the labels will also be HTML-encoded.
1795
     * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
1796
     * This method will take out these elements, if any: "prompt", "options" and "groups". See more details
1797
     * in [[dropDownList()]] for the explanation of these elements.
1798
     *
1799
     * @return string the generated list options
1800
     */
1801 8
    public static function renderSelectOptions($selection, $items, &$tagOptions = [])
1802
    {
1803 8
        $lines = [];
1804 8
        $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
1805 8
        $encode = ArrayHelper::remove($tagOptions, 'encode', true);
1806 8
        if (isset($tagOptions['prompt'])) {
1807 3
            $promptOptions = ['value' => ''];
1808 3
            if (is_string($tagOptions['prompt'])) {
1809 3
                $promptText = $tagOptions['prompt'];
1810
            } else {
1811 1
                $promptText = $tagOptions['prompt']['text'];
1812 1
                $promptOptions = array_merge($promptOptions, $tagOptions['prompt']['options']);
1813
            }
1814 3
            $promptText = $encode ? static::encode($promptText) : $promptText;
1815 3
            if ($encodeSpaces) {
1816 1
                $promptText = str_replace(' ', '&nbsp;', $promptText);
1817
            }
1818 3
            $lines[] = static::tag('option', $promptText, $promptOptions);
1819
        }
1820
1821 8
        $options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
1822 8
        $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
1823 8
        unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
1824 8
        $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
1825 8
        $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
1826
1827 8
        foreach ($items as $key => $value) {
1828 7
            if (is_array($value)) {
1829 1
                $groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
1830 1
                if (!isset($groupAttrs['label'])) {
1831 1
                    $groupAttrs['label'] = $key;
1832
                }
1833 1
                $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
1834 1
                $content = static::renderSelectOptions($selection, $value, $attrs);
1835 1
                $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
1836
            } else {
1837 7
                $attrs = isset($options[$key]) ? $options[$key] : [];
1838 7
                $attrs['value'] = (string) $key;
1839 7
                if (!array_key_exists('selected', $attrs)) {
1840 7
                    $attrs['selected'] = $selection !== null &&
1841 5
                        (!ArrayHelper::isTraversable($selection) && !strcmp($key, $selection)
1842 5
                        || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn($key, $selection));
0 ignored issues
show
Bug introduced by
It seems like $selection defined by parameter $selection on line 1801 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...
1843
                }
1844 7
                $text = $encode ? static::encode($value) : $value;
1845 7
                if ($encodeSpaces) {
1846 2
                    $text = str_replace(' ', '&nbsp;', $text);
1847
                }
1848 7
                $lines[] = static::tag('option', $text, $attrs);
1849
            }
1850
        }
1851
1852 8
        return implode("\n", $lines);
1853
    }
1854
1855
    /**
1856
     * Renders the HTML tag attributes.
1857
     *
1858
     * Attributes whose values are of boolean type will be treated as
1859
     * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
1860
     *
1861
     * Attributes whose values are null will not be rendered.
1862
     *
1863
     * The values of attributes will be HTML-encoded using [[encode()]].
1864
     *
1865
     * The "data" attribute is specially handled when it is receiving an array value. In this case,
1866
     * the array will be "expanded" and a list data attributes will be rendered. For example,
1867
     * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered:
1868
     * `data-id="1" data-name="yii"`.
1869
     * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as:
1870
     * `data-params='{"id":1,"name":"yii"}' data-status="ok"`.
1871
     *
1872
     * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
1873
     * @return string the rendering result. If the attributes are not empty, they will be rendered
1874
     * into a string with a leading white space (so that it can be directly appended to the tag name
1875
     * in a tag. If there is no attribute, an empty string will be returned.
1876
     */
1877 214
    public static function renderTagAttributes($attributes)
1878
    {
1879 214
        if (count($attributes) > 1) {
1880 164
            $sorted = [];
1881 164
            foreach (static::$attributeOrder as $name) {
1882 164
                if (isset($attributes[$name])) {
1883 164
                    $sorted[$name] = $attributes[$name];
1884
                }
1885
            }
1886 164
            $attributes = array_merge($sorted, $attributes);
1887
        }
1888
1889 214
        $html = '';
1890 214
        foreach ($attributes as $name => $value) {
1891 205
            if (is_bool($value)) {
1892 32
                if ($value) {
1893 32
                    $html .= " $name";
1894
                }
1895 205
            } elseif (is_array($value)) {
1896 11
                if (in_array($name, static::$dataAttributes)) {
1897 4
                    foreach ($value as $n => $v) {
1898 4
                        if (is_array($v)) {
1899 1
                            $html .= " $name-$n='" . Json::htmlEncode($v) . "'";
1900
                        } else {
1901 4
                            $html .= " $name-$n=\"" . static::encode($v) . '"';
1902
                        }
1903
                    }
1904 9
                } elseif ($name === 'class') {
1905 8
                    if (empty($value)) {
1906 8
                        continue;
1907
                    }
1908 3
                    $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
1909 2
                } elseif ($name === 'style') {
1910 1
                    if (empty($value)) {
1911 1
                        continue;
1912
                    }
1913 1
                    $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
1914
                } else {
1915 6
                    $html .= " $name='" . Json::htmlEncode($value) . "'";
1916
                }
1917 199
            } elseif ($value !== null) {
1918 201
                $html .= " $name=\"" . static::encode($value) . '"';
1919
            }
1920
        }
1921
1922 214
        return $html;
1923
    }
1924
1925
    /**
1926
     * Adds a CSS class (or several classes) to the specified options.
1927
     *
1928
     * If the CSS class is already in the options, it will not be added again.
1929
     * If class specification at given options is an array, and some class placed there with the named (string) key,
1930
     * overriding of such key will have no effect. For example:
1931
     *
1932
     * ```php
1933
     * $options = ['class' => ['persistent' => 'initial']];
1934
     * Html::addCssClass($options, ['persistent' => 'override']);
1935
     * var_dump($options['class']); // outputs: array('persistent' => 'initial');
1936
     * ```
1937
     *
1938
     * @param array $options the options to be modified.
1939
     * @param string|array $class the CSS class(es) to be added
1940
     */
1941 15
    public static function addCssClass(&$options, $class)
1942
    {
1943 15
        if (isset($options['class'])) {
1944 8
            if (is_array($options['class'])) {
1945 3
                $options['class'] = self::mergeCssClasses($options['class'], (array) $class);
1946
            } else {
1947 6
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
1948 8
                $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
1949
            }
1950
        } else {
1951 13
            $options['class'] = $class;
1952
        }
1953 15
    }
1954
1955
    /**
1956
     * Merges already existing CSS classes with new one.
1957
     * This method provides the priority for named existing classes over additional.
1958
     * @param array $existingClasses already existing CSS classes.
1959
     * @param array $additionalClasses CSS classes to be added.
1960
     * @return array merge result.
1961
     */
1962 8
    private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
1963
    {
1964 8
        foreach ($additionalClasses as $key => $class) {
1965 8
            if (is_int($key) && !in_array($class, $existingClasses)) {
1966 7
                $existingClasses[] = $class;
1967 2
            } elseif (!isset($existingClasses[$key])) {
1968 8
                $existingClasses[$key] = $class;
1969
            }
1970
        }
1971
1972 8
        return array_unique($existingClasses);
1973
    }
1974
1975
    /**
1976
     * Removes a CSS class from the specified options.
1977
     * @param array $options the options to be modified.
1978
     * @param string|array $class the CSS class(es) to be removed
1979
     */
1980 1
    public static function removeCssClass(&$options, $class)
1981
    {
1982 1
        if (isset($options['class'])) {
1983 1
            if (is_array($options['class'])) {
1984 1
                $classes = array_diff($options['class'], (array) $class);
1985 1
                if (empty($classes)) {
1986 1
                    unset($options['class']);
1987
                } else {
1988 1
                    $options['class'] = $classes;
1989
                }
1990
            } else {
1991 1
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
1992 1
                $classes = array_diff($classes, (array) $class);
1993 1
                if (empty($classes)) {
1994 1
                    unset($options['class']);
1995
                } else {
1996 1
                    $options['class'] = implode(' ', $classes);
1997
                }
1998
            }
1999
        }
2000 1
    }
2001
2002
    /**
2003
     * Adds the specified CSS style to the HTML options.
2004
     *
2005
     * If the options already contain a `style` element, the new style will be merged
2006
     * with the existing one. If a CSS property exists in both the new and the old styles,
2007
     * the old one may be overwritten if `$overwrite` is true.
2008
     *
2009
     * For example,
2010
     *
2011
     * ```php
2012
     * Html::addCssStyle($options, 'width: 100px; height: 200px');
2013
     * ```
2014
     *
2015
     * @param array $options the HTML options to be modified.
2016
     * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
2017
     * array (e.g. `['width' => '100px', 'height' => '200px']`).
2018
     * @param bool $overwrite whether to overwrite existing CSS properties if the new style
2019
     * contain them too.
2020
     * @see removeCssStyle()
2021
     * @see cssStyleFromArray()
2022
     * @see cssStyleToArray()
2023
     */
2024 1
    public static function addCssStyle(&$options, $style, $overwrite = true)
2025
    {
2026 1
        if (!empty($options['style'])) {
2027 1
            $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
2028 1
            $newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
2029 1
            if (!$overwrite) {
2030 1
                foreach ($newStyle as $property => $value) {
2031 1
                    if (isset($oldStyle[$property])) {
2032 1
                        unset($newStyle[$property]);
2033
                    }
2034
                }
2035
            }
2036 1
            $style = array_merge($oldStyle, $newStyle);
2037
        }
2038 1
        $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
2039 1
    }
2040
2041
    /**
2042
     * Removes the specified CSS style from the HTML options.
2043
     *
2044
     * For example,
2045
     *
2046
     * ```php
2047
     * Html::removeCssStyle($options, ['width', 'height']);
2048
     * ```
2049
     *
2050
     * @param array $options the HTML options to be modified.
2051
     * @param string|array $properties the CSS properties to be removed. You may use a string
2052
     * if you are removing a single property.
2053
     * @see addCssStyle()
2054
     */
2055 1
    public static function removeCssStyle(&$options, $properties)
2056
    {
2057 1
        if (!empty($options['style'])) {
2058 1
            $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
2059 1
            foreach ((array) $properties as $property) {
2060 1
                unset($style[$property]);
2061
            }
2062 1
            $options['style'] = static::cssStyleFromArray($style);
2063
        }
2064 1
    }
2065
2066
    /**
2067
     * Converts a CSS style array into a string representation.
2068
     *
2069
     * For example,
2070
     *
2071
     * ```php
2072
     * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
2073
     * // will display: 'width: 100px; height: 200px;'
2074
     * ```
2075
     *
2076
     * @param array $style the CSS style array. The array keys are the CSS property names,
2077
     * and the array values are the corresponding CSS property values.
2078
     * @return string the CSS style string. If the CSS style is empty, a null will be returned.
2079
     */
2080 4
    public static function cssStyleFromArray(array $style)
2081
    {
2082 4
        $result = '';
2083 4
        foreach ($style as $name => $value) {
2084 4
            $result .= "$name: $value; ";
2085
        }
2086
        // return null if empty to avoid rendering the "style" attribute
2087 4
        return $result === '' ? null : rtrim($result);
2088
    }
2089
2090
    /**
2091
     * Converts a CSS style string into an array representation.
2092
     *
2093
     * The array keys are the CSS property names, and the array values
2094
     * are the corresponding CSS property values.
2095
     *
2096
     * For example,
2097
     *
2098
     * ```php
2099
     * print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
2100
     * // will display: ['width' => '100px', 'height' => '200px']
2101
     * ```
2102
     *
2103
     * @param string $style the CSS style string
2104
     * @return array the array representation of the CSS style
2105
     */
2106 3
    public static function cssStyleToArray($style)
2107
    {
2108 3
        $result = [];
2109 3
        foreach (explode(';', $style) as $property) {
2110 3
            $property = explode(':', $property);
2111 3
            if (count($property) > 1) {
2112 3
                $result[trim($property[0])] = trim($property[1]);
2113
            }
2114
        }
2115
2116 3
        return $result;
2117
    }
2118
2119
    /**
2120
     * Returns the real attribute name from the given attribute expression.
2121
     *
2122
     * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
2123
     * It is mainly used in tabular data input and/or input of array type. Below are some examples:
2124
     *
2125
     * - `[0]content` is used in tabular data input to represent the "content" attribute
2126
     *   for the first model in tabular input;
2127
     * - `dates[0]` represents the first array element of the "dates" attribute;
2128
     * - `[0]dates[0]` represents the first array element of the "dates" attribute
2129
     *   for the first model in tabular input.
2130
     *
2131
     * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
2132
     * @param string $attribute the attribute name or expression
2133
     * @return string the attribute name without prefix and suffix.
2134
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2135
     */
2136 48
    public static function getAttributeName($attribute)
2137
    {
2138 48
        if (preg_match(static::$attributeRegex, $attribute, $matches)) {
2139 45
            return $matches[2];
2140
        }
2141
2142 3
        throw new InvalidArgumentException('Attribute name must contain word characters only.');
2143
    }
2144
2145
    /**
2146
     * Returns the value of the specified attribute name or expression.
2147
     *
2148
     * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
2149
     * See [[getAttributeName()]] for more details about attribute expression.
2150
     *
2151
     * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
2152
     * the primary value(s) of the AR instance(s) will be returned instead.
2153
     *
2154
     * @param Model $model the model object
2155
     * @param string $attribute the attribute name or expression
2156
     * @return string|array the corresponding attribute value
2157
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2158
     */
2159 52
    public static function getAttributeValue($model, $attribute)
2160
    {
2161 52
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2162 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2163
        }
2164 51
        $attribute = $matches[2];
2165 51
        $value = $model->$attribute;
2166 51
        if ($matches[3] !== '') {
2167
            foreach (explode('][', trim($matches[3], '[]')) as $id) {
2168
                if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
2169
                    $value = $value[$id];
2170
                } else {
2171
                    return null;
2172
                }
2173
            }
2174
        }
2175
2176
        // https://github.com/yiisoft/yii2/issues/1457
2177 51
        if (is_array($value)) {
2178 1
            foreach ($value as $i => $v) {
2179 1
                if ($v instanceof ActiveRecordInterface) {
2180 1
                    $v = $v->getPrimaryKey(false);
2181 1
                    $value[$i] = is_array($v) ? json_encode($v) : $v;
2182
                }
2183
            }
2184 51
        } elseif ($value instanceof ActiveRecordInterface) {
2185 1
            $value = $value->getPrimaryKey(false);
2186
2187 1
            return is_array($value) ? json_encode($value) : $value;
2188
        }
2189
2190 51
        return $value;
2191
    }
2192
2193
    /**
2194
     * Generates an appropriate input name for the specified attribute name or expression.
2195
     *
2196
     * This method generates a name that can be used as the input name to collect user input
2197
     * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
2198
     * of the model and the given attribute name. For example, if the form name of the `Post` model
2199
     * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
2200
     *
2201
     * See [[getAttributeName()]] for explanation of attribute expression.
2202
     *
2203
     * @param Model $model the model object
2204
     * @param string $attribute the attribute name or expression
2205
     * @return string the generated input name
2206
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2207
     */
2208 63
    public static function getInputName($model, $attribute)
2209
    {
2210 63
        $formName = $model->formName();
2211 63
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2212 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2213
        }
2214 62
        $prefix = $matches[1];
2215 62
        $attribute = $matches[2];
2216 62
        $suffix = $matches[3];
2217 62
        if ($formName === '' && $prefix === '') {
2218 1
            return $attribute . $suffix;
2219 61
        } elseif ($formName !== '') {
2220 60
            return $formName . $prefix . "[$attribute]" . $suffix;
2221
        }
2222
2223 1
        throw new InvalidArgumentException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
2224
    }
2225
2226
    /**
2227
     * Generates an appropriate input ID for the specified attribute name or expression.
2228
     *
2229
     * This method converts the result [[getInputName()]] into a valid input ID.
2230
     * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
2231
     * @param Model $model the model object
2232
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
2233
     * @return string the generated input ID
2234
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2235
     */
2236 50
    public static function getInputId($model, $attribute)
2237
    {
2238 50
        $name = strtolower(static::getInputName($model, $attribute));
2239 50
        return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
2240
    }
2241
2242
    /**
2243
     * Escapes regular expression to use in JavaScript.
2244
     * @param string $regexp the regular expression to be escaped.
2245
     * @return string the escaped result.
2246
     * @since 2.0.6
2247
     */
2248 1
    public static function escapeJsRegularExpression($regexp)
2249
    {
2250 1
        $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
2251 1
        $deliminator = substr($pattern, 0, 1);
2252 1
        $pos = strrpos($pattern, $deliminator, 1);
2253 1
        $flag = substr($pattern, $pos + 1);
2254 1
        if ($deliminator !== '/') {
2255 1
            $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
2256
        } else {
2257 1
            $pattern = substr($pattern, 0, $pos + 1);
2258
        }
2259 1
        if (!empty($flag)) {
2260 1
            $pattern .= preg_replace('/[^igm]/', '', $flag);
2261
        }
2262
2263 1
        return $pattern;
2264
    }
2265
}
2266