Completed
Push — 2.1 ( fd9384...61dec0 )
by Alexander
08:39
created

BaseHtml   D

Complexity

Total Complexity 258

Size/Duplication

Total Lines 2213
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Test Coverage

Coverage 99.28%

Importance

Changes 0
Metric Value
wmc 258
lcom 1
cbo 10
dl 0
loc 2213
ccs 548
cts 552
cp 0.9928
rs 4.4102
c 0
b 0
f 0

72 Methods

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

How to fix   Complexity   

Complex Class

Complex classes like BaseHtml often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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

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

1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\helpers;
9
10
use Yii;
11
use yii\base\InvalidArgumentException;
12
use yii\base\Model;
13
use yii\db\ActiveRecordInterface;
14
use yii\validators\StringValidator;
15
use yii\web\Request;
16
17
/**
18
 * BaseHtml provides concrete implementation for [[Html]].
19
 *
20
 * Do not use BaseHtml. Use [[Html]] instead.
21
 *
22
 * @author Qiang Xue <[email protected]>
23
 * @since 2.0
24
 */
25
class BaseHtml
26
{
27
    /**
28
     * @var string Regular expression used for attribute name validation.
29
     * @since 2.0.12
30
     */
31
    public static $attributeRegex = '/(^|.*\])([\w\.\+]+)(\[.*|$)/u';
32
    /**
33
     * @var array list of void elements (element name => 1)
34
     * @see http://www.w3.org/TR/html-markup/syntax.html#void-element
35
     */
36
    public static $voidElements = [
37
        'area' => 1,
38
        'base' => 1,
39
        'br' => 1,
40
        'col' => 1,
41
        'command' => 1,
42
        'embed' => 1,
43
        'hr' => 1,
44
        'img' => 1,
45
        'input' => 1,
46
        'keygen' => 1,
47
        'link' => 1,
48
        'meta' => 1,
49
        'param' => 1,
50
        'source' => 1,
51
        'track' => 1,
52
        'wbr' => 1,
53
    ];
54
    /**
55
     * @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes
56
     * that are rendered by [[renderTagAttributes()]].
57
     */
58
    public static $attributeOrder = [
59
        'type',
60
        'id',
61
        'class',
62
        'name',
63
        'value',
64
65
        'href',
66
        'src',
67
        'srcset',
68
        'form',
69
        'action',
70
        'method',
71
72
        'selected',
73
        'checked',
74
        'readonly',
75
        'disabled',
76
        'multiple',
77
78
        'size',
79
        'maxlength',
80
        'width',
81
        'height',
82
        'rows',
83
        'cols',
84
85
        'alt',
86
        'title',
87
        'rel',
88
        'media',
89
    ];
90
    /**
91
     * @var array list of tag attributes that should be specially handled when their values are of array type.
92
     * In particular, if the value of the `data` attribute is `['name' => 'xyz', 'age' => 13]`, two attributes
93
     * will be generated instead of one: `data-name="xyz" data-age="13"`.
94
     * @since 2.0.3
95
     */
96
    public static $dataAttributes = ['data', 'data-ng', 'ng'];
97
98
99
    /**
100
     * Encodes special characters into HTML entities.
101
     * The [[\yii\base\Application::charset|application charset]] will be used for encoding.
102
     * @param string $content the content to be encoded
103
     * @param bool $doubleEncode whether to encode HTML entities in `$content`. If false,
104
     * HTML entities in `$content` will not be further encoded.
105
     * @return string the encoded content
106
     * @see decode()
107
     * @see 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 19
    public static function a($text, $url = null, $options = [])
410
    {
411 19
        if ($url !== null) {
412 19
            $options['href'] = Url::to($url);
413
        }
414
415 19
        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 81
    public static function input($type, $name = null, $value = null, $options = [])
557
    {
558 81
        if (!isset($options['type'])) {
559 81
            $options['type'] = $type;
560
        }
561 81
        $options['name'] = $name;
562 81
        $options['value'] = $value === null ? null : (string) $value;
563 81
        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
1220 7
        $lines = [];
1221 7
        if (!is_array($models)) {
1222 7
            $models = [$models];
1223
        }
1224 7
        foreach ($models as $model) {
1225
            /* @var $model Model */
1226 7
            foreach ($model->getErrors() as $errors) {
1227 5
                foreach ($errors as $error) {
1228 5
                    $line = $encode ? Html::encode($error) : $error;
1229 5
                    if (!in_array($line, $lines, true)) {
1230 5
                        $lines[] = $line;
1231
                    }
1232 5
                    if (!$showAllErrors) {
1233 7
                        break;
1234
                    }
1235
                }
1236
            }
1237
        }
1238
1239 7
        if (empty($lines)) {
1240
            // still render the placeholder for client-side validation use
1241 2
            $content = '<ul></ul>';
1242 2
            $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
1243
        } else {
1244 5
            $content = '<ul><li>' . implode("</li>\n<li>", $lines) . '</li></ul>';
1245
        }
1246
1247 7
        return Html::tag('div', $header . $content . $footer, $options);
1248
    }
1249
1250
    /**
1251
     * Generates a tag that contains the first validation error of the specified model attribute.
1252
     * Note that even if there is no validation error, this method will still return an empty error tag.
1253
     * @param Model $model the model object
1254
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1255
     * about attribute expression.
1256
     * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
1257
     * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1258
     *
1259
     * The following options are specially handled:
1260
     *
1261
     * - tag: this specifies the tag name. If not set, "div" will be used.
1262
     *   See also [[tag()]].
1263
     * - encode: boolean, if set to false then the error message won't be encoded.
1264
     *
1265
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1266
     *
1267
     * @return string the generated label tag
1268
     */
1269 9
    public static function error($model, $attribute, $options = [])
1270
    {
1271 9
        $attribute = static::getAttributeName($attribute);
1272 9
        $error = $model->getFirstError($attribute);
1273 9
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1274 9
        $encode = ArrayHelper::remove($options, 'encode', true);
1275 9
        return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
1276
    }
1277
1278
    /**
1279
     * Generates an input tag for the given model attribute.
1280
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1281
     * unless they are explicitly specified in `$options`.
1282
     * @param string $type the input type (e.g. 'text', 'password')
1283
     * @param Model $model the model object
1284
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1285
     * about attribute expression.
1286
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1287
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1288
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1289
     * @return string the generated input tag
1290
     */
1291 30
    public static function activeInput($type, $model, $attribute, $options = [])
1292
    {
1293 30
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1294 30
        $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1295 30
        if (!array_key_exists('id', $options)) {
1296 20
            $options['id'] = static::getInputId($model, $attribute);
1297
        }
1298
1299 30
        return static::input($type, $name, $value, $options);
1300
    }
1301
1302
    /**
1303
     * If `maxlength` option is set true and the model attribute is validated by a string validator,
1304
     * the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1305
     * @param Model $model the model object
1306
     * @param string $attribute the attribute name or expression.
1307
     * @param array $options the tag options in terms of name-value pairs.
1308
     */
1309 27
    private static function normalizeMaxLength($model, $attribute, &$options)
1310
    {
1311 27
        if (isset($options['maxlength']) && $options['maxlength'] === true) {
1312 3
            unset($options['maxlength']);
1313 3
            $attrName = static::getAttributeName($attribute);
1314 3
            foreach ($model->getActiveValidators($attrName) as $validator) {
1315 3
                if ($validator instanceof StringValidator && $validator->max !== null) {
1316 3
                    $options['maxlength'] = $validator->max;
1317 3
                    break;
1318
                }
1319
            }
1320
        }
1321 27
    }
1322
1323
    /**
1324
     * Generates a text input tag for the given model attribute.
1325
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1326
     * unless they are explicitly specified in `$options`.
1327
     * @param Model $model the model object
1328
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1329
     * about attribute expression.
1330
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1331
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1332
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1333
     * The following special options are recognized:
1334
     *
1335
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1336
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1337
     *   This is available since version 2.0.3.
1338
     *
1339
     * @return string the generated input tag
1340
     */
1341 20
    public static function activeTextInput($model, $attribute, $options = [])
1342
    {
1343 20
        self::normalizeMaxLength($model, $attribute, $options);
1344 20
        return static::activeInput('text', $model, $attribute, $options);
1345
    }
1346
1347
    /**
1348
     * Generates a hidden input tag for the given model attribute.
1349
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1350
     * unless they are explicitly specified in `$options`.
1351
     * @param Model $model the model object
1352
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1353
     * about attribute expression.
1354
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1355
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1356
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1357
     * @return string the generated input tag
1358
     */
1359 5
    public static function activeHiddenInput($model, $attribute, $options = [])
1360
    {
1361 5
        return static::activeInput('hidden', $model, $attribute, $options);
1362
    }
1363
1364
    /**
1365
     * Generates a password input tag for the given model attribute.
1366
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1367
     * unless they are explicitly specified in `$options`.
1368
     * @param Model $model the model object
1369
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1370
     * about attribute expression.
1371
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1372
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1373
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1374
     * The following special options are recognized:
1375
     *
1376
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1377
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1378
     *   This option is available since version 2.0.6.
1379
     *
1380
     * @return string the generated input tag
1381
     */
1382 3
    public static function activePasswordInput($model, $attribute, $options = [])
1383
    {
1384 3
        self::normalizeMaxLength($model, $attribute, $options);
1385 3
        return static::activeInput('password', $model, $attribute, $options);
1386
    }
1387
1388
    /**
1389
     * Generates a file input tag for the given model attribute.
1390
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1391
     * unless they are explicitly specified in `$options`.
1392
     * @param Model $model the model object
1393
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1394
     * about attribute expression.
1395
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1396
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1397
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1398
     * @return string the generated input tag
1399
     */
1400 2
    public static function activeFileInput($model, $attribute, $options = [])
1401
    {
1402
        // add a hidden field so that if a model only has a file field, we can
1403
        // still use isset($_POST[$modelClass]) to detect if the input is submitted
1404 2
        $hiddenOptions = ['id' => null, 'value' => ''];
1405 2
        if (isset($options['name'])) {
1406 1
            $hiddenOptions['name'] = $options['name'];
1407
        }
1408
1409 2
        return static::activeHiddenInput($model, $attribute, $hiddenOptions)
1410 2
            . static::activeInput('file', $model, $attribute, $options);
1411
    }
1412
1413
    /**
1414
     * Generates a textarea tag for the given model attribute.
1415
     * The model attribute value will be used as the content in the textarea.
1416
     * @param Model $model the model object
1417
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1418
     * about attribute expression.
1419
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1420
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1421
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1422
     * The following special options are recognized:
1423
     *
1424
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1425
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1426
     *   This option is available since version 2.0.6.
1427
     *
1428
     * @return string the generated textarea tag
1429
     */
1430 4
    public static function activeTextarea($model, $attribute, $options = [])
1431
    {
1432 4
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1433 4
        if (isset($options['value'])) {
1434 1
            $value = $options['value'];
1435 1
            unset($options['value']);
1436
        } else {
1437 3
            $value = static::getAttributeValue($model, $attribute);
1438
        }
1439 4
        if (!array_key_exists('id', $options)) {
1440 4
            $options['id'] = static::getInputId($model, $attribute);
1441
        }
1442 4
        self::normalizeMaxLength($model, $attribute, $options);
1443 4
        return static::textarea($name, $value, $options);
1444
    }
1445
1446
    /**
1447
     * Generates a radio button tag together with a label for the given model attribute.
1448
     * This method will generate the "checked" tag attribute according to the model attribute value.
1449
     * @param Model $model the model object
1450
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1451
     * about attribute expression.
1452
     * @param array $options the tag options in terms of name-value pairs.
1453
     * See [[booleanInput()]] for details about accepted attributes.
1454
     *
1455
     * @return string the generated radio button tag
1456
     */
1457 4
    public static function activeRadio($model, $attribute, $options = [])
1458
    {
1459 4
        return static::activeBooleanInput('radio', $model, $attribute, $options);
1460
    }
1461
1462
    /**
1463
     * Generates a checkbox tag together with a label for the given model attribute.
1464
     * This method will generate the "checked" tag attribute according to the model attribute value.
1465
     * @param Model $model the model object
1466
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1467
     * about attribute expression.
1468
     * @param array $options the tag options in terms of name-value pairs.
1469
     * See [[booleanInput()]] for details about accepted attributes.
1470
     *
1471
     * @return string the generated checkbox tag
1472
     */
1473 4
    public static function activeCheckbox($model, $attribute, $options = [])
1474
    {
1475 4
        return static::activeBooleanInput('checkbox', $model, $attribute, $options);
1476
    }
1477
1478
    /**
1479
     * Generates a boolean input
1480
     * This method is mainly called by [[activeCheckbox()]] and [[activeRadio()]].
1481
     * @param string $type the input type. This can be either `radio` or `checkbox`.
1482
     * @param Model $model the model object
1483
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1484
     * about attribute expression.
1485
     * @param array $options the tag options in terms of name-value pairs.
1486
     * See [[booleanInput()]] for details about accepted attributes.
1487
     * @return string the generated input element
1488
     * @since 2.0.9
1489
     */
1490 8
    protected static function activeBooleanInput($type, $model, $attribute, $options = [])
1491
    {
1492 8
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1493 8
        $value = static::getAttributeValue($model, $attribute);
1494
1495 8
        if (!array_key_exists('value', $options)) {
1496 8
            $options['value'] = '1';
1497
        }
1498 8
        if (!array_key_exists('uncheck', $options)) {
1499 4
            $options['uncheck'] = '0';
1500 4
        } elseif ($options['uncheck'] === false) {
1501 4
            unset($options['uncheck']);
1502
        }
1503 8
        if (!array_key_exists('label', $options)) {
1504 4
            $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
1505 4
        } elseif ($options['label'] === false) {
1506 4
            unset($options['label']);
1507
        }
1508
1509 8
        $checked = "$value" === "{$options['value']}";
1510
1511 8
        if (!array_key_exists('id', $options)) {
1512 8
            $options['id'] = static::getInputId($model, $attribute);
1513
        }
1514
1515 8
        return static::$type($name, $checked, $options);
1516
    }
1517
1518
    /**
1519
     * Generates a drop-down list for the given model attribute.
1520
     * The selection of the drop-down list is taken from the value of the model attribute.
1521
     * @param Model $model the model object
1522
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1523
     * about attribute expression.
1524
     * @param array $items the option data items. The array keys are option values, and the array values
1525
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1526
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1527
     * If you have a list of data models, you may convert them into the format described above using
1528
     * [[\yii\helpers\ArrayHelper::map()]].
1529
     *
1530
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1531
     * the labels will also be HTML-encoded.
1532
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1533
     *
1534
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1535
     *   to override the value and to set other tag attributes:
1536
     *
1537
     *   ```php
1538
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1539
     *   ```
1540
     *
1541
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1542
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1543
     *
1544
     *   ```php
1545
     *   [
1546
     *       'value1' => ['disabled' => true],
1547
     *       'value2' => ['label' => 'value 2'],
1548
     *   ];
1549
     *   ```
1550
     *
1551
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1552
     *   except that the array keys represent the optgroup labels specified in $items.
1553
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1554
     *   Defaults to false.
1555
     * - encode: bool, whether to encode option prompt and option value characters.
1556
     *   Defaults to `true`. This option is available since 2.0.3.
1557
     *
1558
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1559
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1560
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1561
     *
1562
     * @return string the generated drop-down list tag
1563
     */
1564 3
    public static function activeDropDownList($model, $attribute, $items, $options = [])
1565
    {
1566 3
        if (empty($options['multiple'])) {
1567 2
            return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
1568
        }
1569
1570 1
        return static::activeListBox($model, $attribute, $items, $options);
1571
    }
1572
1573
    /**
1574
     * Generates a list box.
1575
     * The selection of the list box is taken from the value of the model attribute.
1576
     * @param Model $model the model object
1577
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1578
     * about attribute expression.
1579
     * @param array $items the option data items. The array keys are option values, and the array values
1580
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1581
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1582
     * If you have a list of data models, you may convert them into the format described above using
1583
     * [[\yii\helpers\ArrayHelper::map()]].
1584
     *
1585
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1586
     * the labels will also be HTML-encoded.
1587
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1588
     *
1589
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1590
     *   to override the value and to set other tag attributes:
1591
     *
1592
     *   ```php
1593
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1594
     *   ```
1595
     *
1596
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1597
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1598
     *
1599
     *   ```php
1600
     *   [
1601
     *       'value1' => ['disabled' => true],
1602
     *       'value2' => ['label' => 'value 2'],
1603
     *   ];
1604
     *   ```
1605
     *
1606
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1607
     *   except that the array keys represent the optgroup labels specified in $items.
1608
     * - unselect: string, the value that will be submitted when no option is selected.
1609
     *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
1610
     *   mode, we can still obtain the posted unselect value.
1611
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1612
     *   Defaults to false.
1613
     * - encode: bool, whether to encode option prompt and option value characters.
1614
     *   Defaults to `true`. This option is available since 2.0.3.
1615
     *
1616
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1617
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1618
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1619
     *
1620
     * @return string the generated list box tag
1621
     */
1622 3
    public static function activeListBox($model, $attribute, $items, $options = [])
1623
    {
1624 3
        return static::activeListInput('listBox', $model, $attribute, $items, $options);
1625
    }
1626
1627
    /**
1628
     * Generates a list of checkboxes.
1629
     * A checkbox list allows multiple selection, like [[listBox()]].
1630
     * As a result, the corresponding submitted value is an array.
1631
     * The selection of the checkbox list is taken from the value of the model attribute.
1632
     * @param Model $model the model object
1633
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1634
     * about attribute expression.
1635
     * @param array $items the data item used to generate the checkboxes.
1636
     * The array keys are the checkbox values, and the array values are the corresponding labels.
1637
     * Note that the labels will NOT be HTML-encoded, while the values will.
1638
     * @param array $options options (name => config) for the checkbox list container tag.
1639
     * The following options are specially handled:
1640
     *
1641
     * - tag: string|false, the tag name of the container element. False to render checkbox without container.
1642
     *   See also [[tag()]].
1643
     * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
1644
     *   You may set this option to be null to prevent default value submission.
1645
     *   If this option is not set, an empty string will be submitted.
1646
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1647
     *   This option is ignored if `item` option is set.
1648
     * - separator: string, the HTML code that separates items.
1649
     * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
1650
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1651
     *   corresponding to a single item in $items. The signature of this callback must be:
1652
     *
1653
     *   ```php
1654
     *   function ($index, $label, $name, $checked, $value)
1655
     *   ```
1656
     *
1657
     *   where $index is the zero-based index of the checkbox in the whole list; $label
1658
     *   is the label for the checkbox; and $name, $value and $checked represent the name,
1659
     *   value and the checked status of the checkbox input.
1660
     *
1661
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1662
     *
1663
     * @return string the generated checkbox list
1664
     */
1665 1
    public static function activeCheckboxList($model, $attribute, $items, $options = [])
1666
    {
1667 1
        return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
1668
    }
1669
1670
    /**
1671
     * Generates a list of radio buttons.
1672
     * A radio button list is like a checkbox list, except that it only allows single selection.
1673
     * The selection of the radio buttons is taken from the value of the model attribute.
1674
     * @param Model $model the model object
1675
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1676
     * about attribute expression.
1677
     * @param array $items the data item used to generate the radio buttons.
1678
     * The array keys are the radio values, and the array values are the corresponding labels.
1679
     * Note that the labels will NOT be HTML-encoded, while the values will.
1680
     * @param array $options options (name => config) for the radio button list container tag.
1681
     * The following options are specially handled:
1682
     *
1683
     * - tag: string|false, the tag name of the container element. False to render radio button without container.
1684
     *   See also [[tag()]].
1685
     * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
1686
     *   You may set this option to be null to prevent default value submission.
1687
     *   If this option is not set, an empty string will be submitted.
1688
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1689
     *   This option is ignored if `item` option is set.
1690
     * - separator: string, the HTML code that separates items.
1691
     * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
1692
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1693
     *   corresponding to a single item in $items. The signature of this callback must be:
1694
     *
1695
     *   ```php
1696
     *   function ($index, $label, $name, $checked, $value)
1697
     *   ```
1698
     *
1699
     *   where $index is the zero-based index of the radio button in the whole list; $label
1700
     *   is the label for the radio button; and $name, $value and $checked represent the name,
1701
     *   value and the checked status of the radio button input.
1702
     *
1703
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1704
     *
1705
     * @return string the generated radio button list
1706
     */
1707 1
    public static function activeRadioList($model, $attribute, $items, $options = [])
1708
    {
1709 1
        return static::activeListInput('radioList', $model, $attribute, $items, $options);
1710
    }
1711
1712
    /**
1713
     * Generates a list of input fields.
1714
     * This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckboxList()]].
1715
     * @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'.
1716
     * @param Model $model the model object
1717
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1718
     * about attribute expression.
1719
     * @param array $items the data item used to generate the input fields.
1720
     * The array keys are the input values, and the array values are the corresponding labels.
1721
     * Note that the labels will NOT be HTML-encoded, while the values will.
1722
     * @param array $options options (name => config) for the input list. The supported special options
1723
     * depend on the input type specified by `$type`.
1724
     * @return string the generated input list
1725
     */
1726 7
    protected static function activeListInput($type, $model, $attribute, $items, $options = [])
1727
    {
1728 7
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1729 7
        $selection = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1730 7
        if (!array_key_exists('unselect', $options)) {
1731 7
            $options['unselect'] = '';
1732
        }
1733 7
        if (!array_key_exists('id', $options)) {
1734 5
            $options['id'] = static::getInputId($model, $attribute);
1735
        }
1736
1737 7
        return static::$type($name, $selection, $items, $options);
1738
    }
1739
1740
    /**
1741
     * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
1742
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
1743
     * @param array $items the option data items. The array keys are option values, and the array values
1744
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1745
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1746
     * If you have a list of data models, you may convert them into the format described above using
1747
     * [[\yii\helpers\ArrayHelper::map()]].
1748
     *
1749
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1750
     * the labels will also be HTML-encoded.
1751
     * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
1752
     * This method will take out these elements, if any: "prompt", "options" and "groups". See more details
1753
     * in [[dropDownList()]] for the explanation of these elements.
1754
     *
1755
     * @return string the generated list options
1756
     */
1757 8
    public static function renderSelectOptions($selection, $items, &$tagOptions = [])
1758
    {
1759 8
        $lines = [];
1760 8
        $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
1761 8
        $encode = ArrayHelper::remove($tagOptions, 'encode', true);
1762 8
        if (isset($tagOptions['prompt'])) {
1763 3
            $promptOptions = ['value' => ''];
1764 3
            if (is_string($tagOptions['prompt'])) {
1765 3
                $promptText = $tagOptions['prompt'];
1766
            } else {
1767 1
                $promptText = $tagOptions['prompt']['text'];
1768 1
                $promptOptions = array_merge($promptOptions, $tagOptions['prompt']['options']);
1769
            }
1770 3
            $promptText = $encode ? static::encode($promptText) : $promptText;
1771 3
            if ($encodeSpaces) {
1772 1
                $promptText = str_replace(' ', '&nbsp;', $promptText);
1773
            }
1774 3
            $lines[] = static::tag('option', $promptText, $promptOptions);
1775
        }
1776
1777 8
        $options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
1778 8
        $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
1779 8
        unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
1780 8
        $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
1781 8
        $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
1782
1783 8
        foreach ($items as $key => $value) {
1784 7
            if (is_array($value)) {
1785 1
                $groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
1786 1
                if (!isset($groupAttrs['label'])) {
1787 1
                    $groupAttrs['label'] = $key;
1788
                }
1789 1
                $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
1790 1
                $content = static::renderSelectOptions($selection, $value, $attrs);
1791 1
                $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
1792
            } else {
1793 7
                $attrs = isset($options[$key]) ? $options[$key] : [];
1794 7
                $attrs['value'] = (string) $key;
1795 7
                if (!array_key_exists('selected', $attrs)) {
1796 7
                    $attrs['selected'] = $selection !== null &&
1797 5
                        (!ArrayHelper::isTraversable($selection) && !strcmp($key, $selection)
1798 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 1757 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...
1799
                }
1800 7
                $text = $encode ? static::encode($value) : $value;
1801 7
                if ($encodeSpaces) {
1802 2
                    $text = str_replace(' ', '&nbsp;', $text);
1803
                }
1804 7
                $lines[] = static::tag('option', $text, $attrs);
1805
            }
1806
        }
1807
1808 8
        return implode("\n", $lines);
1809
    }
1810
1811
    /**
1812
     * Renders the HTML tag attributes.
1813
     *
1814
     * Attributes whose values are of boolean type will be treated as
1815
     * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
1816
     *
1817
     * Attributes whose values are null will not be rendered.
1818
     *
1819
     * The values of attributes will be HTML-encoded using [[encode()]].
1820
     *
1821
     * The "data" attribute is specially handled when it is receiving an array value. In this case,
1822
     * the array will be "expanded" and a list data attributes will be rendered. For example,
1823
     * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered:
1824
     * `data-id="1" data-name="yii"`.
1825
     * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as:
1826
     * `data-params='{"id":1,"name":"yii"}' data-status="ok"`.
1827
     *
1828
     * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
1829
     * @return string the rendering result. If the attributes are not empty, they will be rendered
1830
     * into a string with a leading white space (so that it can be directly appended to the tag name
1831
     * in a tag. If there is no attribute, an empty string will be returned.
1832
     */
1833 214
    public static function renderTagAttributes($attributes)
1834
    {
1835 214
        if (count($attributes) > 1) {
1836 165
            $sorted = [];
1837 165
            foreach (static::$attributeOrder as $name) {
1838 165
                if (isset($attributes[$name])) {
1839 165
                    $sorted[$name] = $attributes[$name];
1840
                }
1841
            }
1842 165
            $attributes = array_merge($sorted, $attributes);
1843
        }
1844
1845 214
        $html = '';
1846 214
        foreach ($attributes as $name => $value) {
1847 206
            if (is_bool($value)) {
1848 32
                if ($value) {
1849 32
                    $html .= " $name";
1850
                }
1851 206
            } elseif (is_array($value)) {
1852 11
                if (in_array($name, static::$dataAttributes)) {
1853 4
                    foreach ($value as $n => $v) {
1854 4
                        if (is_array($v)) {
1855 1
                            $html .= " $name-$n='" . Json::htmlEncode($v) . "'";
1856
                        } else {
1857 4
                            $html .= " $name-$n=\"" . static::encode($v) . '"';
1858
                        }
1859
                    }
1860 9
                } elseif ($name === 'class') {
1861 8
                    if (empty($value)) {
1862 8
                        continue;
1863
                    }
1864 3
                    $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
1865 2
                } elseif ($name === 'style') {
1866 1
                    if (empty($value)) {
1867 1
                        continue;
1868
                    }
1869 1
                    $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
1870
                } else {
1871 6
                    $html .= " $name='" . Json::htmlEncode($value) . "'";
1872
                }
1873 200
            } elseif ($value !== null) {
1874 202
                $html .= " $name=\"" . static::encode($value) . '"';
1875
            }
1876
        }
1877
1878 214
        return $html;
1879
    }
1880
1881
    /**
1882
     * Adds a CSS class (or several classes) to the specified options.
1883
     *
1884
     * If the CSS class is already in the options, it will not be added again.
1885
     * If class specification at given options is an array, and some class placed there with the named (string) key,
1886
     * overriding of such key will have no effect. For example:
1887
     *
1888
     * ```php
1889
     * $options = ['class' => ['persistent' => 'initial']];
1890
     * Html::addCssClass($options, ['persistent' => 'override']);
1891
     * var_dump($options['class']); // outputs: array('persistent' => 'initial');
1892
     * ```
1893
     *
1894
     * @param array $options the options to be modified.
1895
     * @param string|array $class the CSS class(es) to be added
1896
     */
1897 15
    public static function addCssClass(&$options, $class)
1898
    {
1899 15
        if (isset($options['class'])) {
1900 8
            if (is_array($options['class'])) {
1901 3
                $options['class'] = self::mergeCssClasses($options['class'], (array) $class);
1902
            } else {
1903 6
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
1904 8
                $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
1905
            }
1906
        } else {
1907 13
            $options['class'] = $class;
1908
        }
1909 15
    }
1910
1911
    /**
1912
     * Merges already existing CSS classes with new one.
1913
     * This method provides the priority for named existing classes over additional.
1914
     * @param array $existingClasses already existing CSS classes.
1915
     * @param array $additionalClasses CSS classes to be added.
1916
     * @return array merge result.
1917
     */
1918 8
    private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
1919
    {
1920 8
        foreach ($additionalClasses as $key => $class) {
1921 8
            if (is_int($key) && !in_array($class, $existingClasses)) {
1922 7
                $existingClasses[] = $class;
1923 2
            } elseif (!isset($existingClasses[$key])) {
1924 8
                $existingClasses[$key] = $class;
1925
            }
1926
        }
1927
1928 8
        return array_unique($existingClasses);
1929
    }
1930
1931
    /**
1932
     * Removes a CSS class from the specified options.
1933
     * @param array $options the options to be modified.
1934
     * @param string|array $class the CSS class(es) to be removed
1935
     */
1936 1
    public static function removeCssClass(&$options, $class)
1937
    {
1938 1
        if (isset($options['class'])) {
1939 1
            if (is_array($options['class'])) {
1940 1
                $classes = array_diff($options['class'], (array) $class);
1941 1
                if (empty($classes)) {
1942 1
                    unset($options['class']);
1943
                } else {
1944 1
                    $options['class'] = $classes;
1945
                }
1946
            } else {
1947 1
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
1948 1
                $classes = array_diff($classes, (array) $class);
1949 1
                if (empty($classes)) {
1950 1
                    unset($options['class']);
1951
                } else {
1952 1
                    $options['class'] = implode(' ', $classes);
1953
                }
1954
            }
1955
        }
1956 1
    }
1957
1958
    /**
1959
     * Adds the specified CSS style to the HTML options.
1960
     *
1961
     * If the options already contain a `style` element, the new style will be merged
1962
     * with the existing one. If a CSS property exists in both the new and the old styles,
1963
     * the old one may be overwritten if `$overwrite` is true.
1964
     *
1965
     * For example,
1966
     *
1967
     * ```php
1968
     * Html::addCssStyle($options, 'width: 100px; height: 200px');
1969
     * ```
1970
     *
1971
     * @param array $options the HTML options to be modified.
1972
     * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
1973
     * array (e.g. `['width' => '100px', 'height' => '200px']`).
1974
     * @param bool $overwrite whether to overwrite existing CSS properties if the new style
1975
     * contain them too.
1976
     * @see removeCssStyle()
1977
     * @see cssStyleFromArray()
1978
     * @see cssStyleToArray()
1979
     */
1980 1
    public static function addCssStyle(&$options, $style, $overwrite = true)
1981
    {
1982 1
        if (!empty($options['style'])) {
1983 1
            $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
1984 1
            $newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
1985 1
            if (!$overwrite) {
1986 1
                foreach ($newStyle as $property => $value) {
1987 1
                    if (isset($oldStyle[$property])) {
1988 1
                        unset($newStyle[$property]);
1989
                    }
1990
                }
1991
            }
1992 1
            $style = array_merge($oldStyle, $newStyle);
1993
        }
1994 1
        $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
1995 1
    }
1996
1997
    /**
1998
     * Removes the specified CSS style from the HTML options.
1999
     *
2000
     * For example,
2001
     *
2002
     * ```php
2003
     * Html::removeCssStyle($options, ['width', 'height']);
2004
     * ```
2005
     *
2006
     * @param array $options the HTML options to be modified.
2007
     * @param string|array $properties the CSS properties to be removed. You may use a string
2008
     * if you are removing a single property.
2009
     * @see addCssStyle()
2010
     */
2011 1
    public static function removeCssStyle(&$options, $properties)
2012
    {
2013 1
        if (!empty($options['style'])) {
2014 1
            $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
2015 1
            foreach ((array) $properties as $property) {
2016 1
                unset($style[$property]);
2017
            }
2018 1
            $options['style'] = static::cssStyleFromArray($style);
2019
        }
2020 1
    }
2021
2022
    /**
2023
     * Converts a CSS style array into a string representation.
2024
     *
2025
     * For example,
2026
     *
2027
     * ```php
2028
     * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
2029
     * // will display: 'width: 100px; height: 200px;'
2030
     * ```
2031
     *
2032
     * @param array $style the CSS style array. The array keys are the CSS property names,
2033
     * and the array values are the corresponding CSS property values.
2034
     * @return string the CSS style string. If the CSS style is empty, a null will be returned.
2035
     */
2036 4
    public static function cssStyleFromArray(array $style)
2037
    {
2038 4
        $result = '';
2039 4
        foreach ($style as $name => $value) {
2040 4
            $result .= "$name: $value; ";
2041
        }
2042
        // return null if empty to avoid rendering the "style" attribute
2043 4
        return $result === '' ? null : rtrim($result);
2044
    }
2045
2046
    /**
2047
     * Converts a CSS style string into an array representation.
2048
     *
2049
     * The array keys are the CSS property names, and the array values
2050
     * are the corresponding CSS property values.
2051
     *
2052
     * For example,
2053
     *
2054
     * ```php
2055
     * print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
2056
     * // will display: ['width' => '100px', 'height' => '200px']
2057
     * ```
2058
     *
2059
     * @param string $style the CSS style string
2060
     * @return array the array representation of the CSS style
2061
     */
2062 3
    public static function cssStyleToArray($style)
2063
    {
2064 3
        $result = [];
2065 3
        foreach (explode(';', $style) as $property) {
2066 3
            $property = explode(':', $property);
2067 3
            if (count($property) > 1) {
2068 3
                $result[trim($property[0])] = trim($property[1]);
2069
            }
2070
        }
2071
2072 3
        return $result;
2073
    }
2074
2075
    /**
2076
     * Returns the real attribute name from the given attribute expression.
2077
     *
2078
     * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
2079
     * It is mainly used in tabular data input and/or input of array type. Below are some examples:
2080
     *
2081
     * - `[0]content` is used in tabular data input to represent the "content" attribute
2082
     *   for the first model in tabular input;
2083
     * - `dates[0]` represents the first array element of the "dates" attribute;
2084
     * - `[0]dates[0]` represents the first array element of the "dates" attribute
2085
     *   for the first model in tabular input.
2086
     *
2087
     * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
2088
     * @param string $attribute the attribute name or expression
2089
     * @return string the attribute name without prefix and suffix.
2090
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2091
     */
2092 47
    public static function getAttributeName($attribute)
2093
    {
2094 47
        if (preg_match(static::$attributeRegex, $attribute, $matches)) {
2095 44
            return $matches[2];
2096
        }
2097
2098 3
        throw new InvalidArgumentException('Attribute name must contain word characters only.');
2099
    }
2100
2101
    /**
2102
     * Returns the value of the specified attribute name or expression.
2103
     *
2104
     * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
2105
     * See [[getAttributeName()]] for more details about attribute expression.
2106
     *
2107
     * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
2108
     * the primary value(s) of the AR instance(s) will be returned instead.
2109
     *
2110
     * @param Model $model the model object
2111
     * @param string $attribute the attribute name or expression
2112
     * @return string|array the corresponding attribute value
2113
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2114
     */
2115 50
    public static function getAttributeValue($model, $attribute)
2116
    {
2117 50
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2118 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2119
        }
2120 49
        $attribute = $matches[2];
2121 49
        $value = $model->$attribute;
2122 49
        if ($matches[3] !== '') {
2123
            foreach (explode('][', trim($matches[3], '[]')) as $id) {
2124
                if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
2125
                    $value = $value[$id];
2126
                } else {
2127
                    return null;
2128
                }
2129
            }
2130
        }
2131
2132
        // https://github.com/yiisoft/yii2/issues/1457
2133 49
        if (is_array($value)) {
2134 1
            foreach ($value as $i => $v) {
2135 1
                if ($v instanceof ActiveRecordInterface) {
2136 1
                    $v = $v->getPrimaryKey(false);
2137 1
                    $value[$i] = is_array($v) ? json_encode($v) : $v;
2138
                }
2139
            }
2140 49
        } elseif ($value instanceof ActiveRecordInterface) {
2141 1
            $value = $value->getPrimaryKey(false);
2142
2143 1
            return is_array($value) ? json_encode($value) : $value;
2144
        }
2145
2146 49
        return $value;
2147
    }
2148
2149
    /**
2150
     * Generates an appropriate input name for the specified attribute name or expression.
2151
     *
2152
     * This method generates a name that can be used as the input name to collect user input
2153
     * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
2154
     * of the model and the given attribute name. For example, if the form name of the `Post` model
2155
     * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
2156
     *
2157
     * See [[getAttributeName()]] for explanation of attribute expression.
2158
     *
2159
     * @param Model $model the model object
2160
     * @param string $attribute the attribute name or expression
2161
     * @return string the generated input name
2162
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2163
     */
2164 61
    public static function getInputName($model, $attribute)
2165
    {
2166 61
        $formName = $model->formName();
2167 61
        if (!preg_match(static::$attributeRegex, $attribute, $matches)) {
2168 1
            throw new InvalidArgumentException('Attribute name must contain word characters only.');
2169
        }
2170 60
        $prefix = $matches[1];
2171 60
        $attribute = $matches[2];
2172 60
        $suffix = $matches[3];
2173 60
        if ($formName === '' && $prefix === '') {
2174 1
            return $attribute . $suffix;
2175 59
        } elseif ($formName !== '') {
2176 58
            return $formName . $prefix . "[$attribute]" . $suffix;
2177
        }
2178
2179 1
        throw new InvalidArgumentException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
2180
    }
2181
2182
    /**
2183
     * Generates an appropriate input ID for the specified attribute name or expression.
2184
     *
2185
     * This method converts the result [[getInputName()]] into a valid input ID.
2186
     * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
2187
     * @param Model $model the model object
2188
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
2189
     * @return string the generated input ID
2190
     * @throws InvalidArgumentException if the attribute name contains non-word characters.
2191
     */
2192 48
    public static function getInputId($model, $attribute)
2193
    {
2194 48
        $name = strtolower(static::getInputName($model, $attribute));
2195 48
        return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
2196
    }
2197
2198
    /**
2199
     * Escapes regular expression to use in JavaScript.
2200
     * @param string $regexp the regular expression to be escaped.
2201
     * @return string the escaped result.
2202
     * @since 2.0.6
2203
     */
2204 1
    public static function escapeJsRegularExpression($regexp)
2205
    {
2206 1
        $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
2207 1
        $deliminator = substr($pattern, 0, 1);
2208 1
        $pos = strrpos($pattern, $deliminator, 1);
2209 1
        $flag = substr($pattern, $pos + 1);
2210 1
        if ($deliminator !== '/') {
2211 1
            $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
2212
        } else {
2213 1
            $pattern = substr($pattern, 0, $pos + 1);
2214
        }
2215 1
        if (!empty($flag)) {
2216 1
            $pattern .= preg_replace('/[^igm]/', '', $flag);
2217
        }
2218
2219 1
        return $pattern;
2220
    }
2221
2222
    /**
2223
     * Returns an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information.
2224
     * @return string an HTML hyperlink that can be displayed on your Web page showing "Powered by Yii Framework" information
2225
     * @since 2.1.0
2226
     */
2227 3
    public static function poweredByYii()
2228
    {
2229 3
        $yiiTitle = Yii::t('yii', 'Yii Framework');
2230 3
        $yiiUrl = 'http://www.yiiframework.com/';
2231 3
        $yiiLink = static::a($yiiTitle, $yiiUrl , ['rel' => 'external']);
2232
2233 3
        return Yii::t('yii', 'Powered by {yii}', [
2234 3
            'yii' => $yiiLink,
2235
        ]);
2236
    }
2237
}
2238