Completed
Push — bash-completion ( 164352...1454d3 )
by Carsten
86:55 queued 83:59
created

BaseHtml::activeCheckbox()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 3
crap 2
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\InvalidParamException;
12
use yii\db\ActiveRecordInterface;
13
use yii\validators\StringValidator;
14
use yii\web\Request;
15
use yii\base\Model;
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 array list of void elements (element name => 1)
29
     * @see http://www.w3.org/TR/html-markup/syntax.html#void-element
30
     */
31
    public static $voidElements = [
32
        'area' => 1,
33
        'base' => 1,
34
        'br' => 1,
35
        'col' => 1,
36
        'command' => 1,
37
        'embed' => 1,
38
        'hr' => 1,
39
        'img' => 1,
40
        'input' => 1,
41
        'keygen' => 1,
42
        'link' => 1,
43
        'meta' => 1,
44
        'param' => 1,
45
        'source' => 1,
46
        'track' => 1,
47
        'wbr' => 1,
48
    ];
49
    /**
50
     * @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes
51
     * that are rendered by [[renderTagAttributes()]].
52
     */
53
    public static $attributeOrder = [
54
        'type',
55
        'id',
56
        'class',
57
        'name',
58
        'value',
59
60
        'href',
61
        'src',
62
        'action',
63
        'method',
64
65
        'selected',
66
        'checked',
67
        'readonly',
68
        'disabled',
69
        'multiple',
70
71
        'size',
72
        'maxlength',
73
        'width',
74
        'height',
75
        'rows',
76
        'cols',
77
78
        'alt',
79
        'title',
80
        'rel',
81
        'media',
82
    ];
83
    /**
84
     * @var array list of tag attributes that should be specially handled when their values are of array type.
85
     * In particular, if the value of the `data` attribute is `['name' => 'xyz', 'age' => 13]`, two attributes
86
     * will be generated instead of one: `data-name="xyz" data-age="13"`.
87
     * @since 2.0.3
88
     */
89
    public static $dataAttributes = ['data', 'data-ng', 'ng'];
90
91
92
    /**
93
     * Encodes special characters into HTML entities.
94
     * The [[\yii\base\Application::charset|application charset]] will be used for encoding.
95
     * @param string $content the content to be encoded
96
     * @param bool $doubleEncode whether to encode HTML entities in `$content`. If false,
97
     * HTML entities in `$content` will not be further encoded.
98
     * @return string the encoded content
99
     * @see decode()
100
     * @see http://www.php.net/manual/en/function.htmlspecialchars.php
101
     */
102 155
    public static function encode($content, $doubleEncode = true)
103
    {
104 155
        return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode);
105
    }
106
107
    /**
108
     * Decodes special HTML entities back to the corresponding characters.
109
     * This is the opposite of [[encode()]].
110
     * @param string $content the content to be decoded
111
     * @return string the decoded content
112
     * @see encode()
113
     * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php
114
     */
115 1
    public static function decode($content)
116
    {
117 1
        return htmlspecialchars_decode($content, ENT_QUOTES);
118
    }
119
120
    /**
121
     * Generates a complete HTML tag.
122
     * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
123
     * @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded.
124
     * If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks.
125
     * @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs.
126
     * These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
127
     * If a value is null, the corresponding attribute will not be rendered.
128
     *
129
     * For example when using `['class' => 'my-class', 'target' => '_blank', 'value' => null]` it will result in the
130
     * html attributes rendered like this: `class="my-class" target="_blank"`.
131
     *
132
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
133
     *
134
     * @return string the generated HTML tag
135
     * @see beginTag()
136
     * @see endTag()
137
     */
138 146
    public static function tag($name, $content = '', $options = [])
139
    {
140 146
        if ($name === null || $name === false) {
141 3
            return $content;
142
        }
143 145
        $html = "<$name" . static::renderTagAttributes($options) . '>';
144 145
        return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>";
145
    }
146
147
    /**
148
     * Generates a start tag.
149
     * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
150
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
151
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
152
     * If a value is null, the corresponding attribute will not be rendered.
153
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
154
     * @return string the generated start tag
155
     * @see endTag()
156
     * @see tag()
157
     */
158 32
    public static function beginTag($name, $options = [])
159
    {
160 32
        if ($name === null || $name === false) {
161 2
            return '';
162
        }
163 32
        return "<$name" . static::renderTagAttributes($options) . '>';
164
    }
165
166
    /**
167
     * Generates an end tag.
168
     * @param string|bool|null $name the tag name. If $name is `null` or `false`, the corresponding content will be rendered without any tag.
169
     * @return string the generated end tag
170
     * @see beginTag()
171
     * @see tag()
172
     */
173 11
    public static function endTag($name)
174
    {
175 11
        if ($name === null || $name === false) {
176 2
            return '';
177
        }
178 11
        return "</$name>";
179
    }
180
181
    /**
182
     * Generates a style tag.
183
     * @param string $content the style content
184
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
185
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
186
     * If a value is null, the corresponding attribute will not be rendered.
187
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
188
     * @return string the generated style tag
189
     */
190 1
    public static function style($content, $options = [])
191
    {
192 1
        return static::tag('style', $content, $options);
193
    }
194
195
    /**
196
     * Generates a script tag.
197
     * @param string $content the script content
198
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
199
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
200
     * If a value is null, the corresponding attribute will not be rendered.
201
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
202
     * @return string the generated script tag
203
     */
204 1
    public static function script($content, $options = [])
205
    {
206 1
        return static::tag('script', $content, $options);
207
    }
208
209
    /**
210
     * Generates a link tag that refers to an external CSS file.
211
     * @param array|string $url the URL of the external CSS file. This parameter will be processed by [[Url::to()]].
212
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
213
     *
214
     * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
215
     *   the generated `link` tag will be enclosed within the conditional comments. This is mainly useful
216
     *   for supporting old versions of IE browsers.
217
     * - noscript: if set to true, `link` tag will be wrapped into `<noscript>` tags.
218
     *
219
     * The rest of the options will be rendered as the attributes of the resulting link tag. The values will
220
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
221
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
222
     * @return string the generated link tag
223
     * @see Url::to()
224
     */
225 20
    public static function cssFile($url, $options = [])
226
    {
227 20
        if (!isset($options['rel'])) {
228 20
            $options['rel'] = 'stylesheet';
229 20
        }
230 20
        $options['href'] = Url::to($url);
231
232 20
        if (isset($options['condition'])) {
233 1
            $condition = $options['condition'];
234 1
            unset($options['condition']);
235 1
            return self::wrapIntoCondition(static::tag('link', '', $options), $condition);
236 20
        } elseif (isset($options['noscript']) && $options['noscript'] === true) {
237
            unset($options['noscript']);
238
            return '<noscript>' . static::tag('link', '', $options) . '</noscript>';
239
        } else {
240 20
            return static::tag('link', '', $options);
241
        }
242
    }
243
244
    /**
245
     * Generates a script tag that refers to an external JavaScript file.
246
     * @param string $url the URL of the external JavaScript file. This parameter will be processed by [[Url::to()]].
247
     * @param array $options the tag options in terms of name-value pairs. The following option is specially handled:
248
     *
249
     * - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
250
     *   the generated `script` tag will be enclosed within the conditional comments. This is mainly useful
251
     *   for supporting old versions of IE browsers.
252
     *
253
     * The rest of the options will be rendered as the attributes of the resulting script tag. The values will
254
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
255
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
256
     * @return string the generated script tag
257
     * @see Url::to()
258
     */
259 22
    public static function jsFile($url, $options = [])
260
    {
261 22
        $options['src'] = Url::to($url);
262 22
        if (isset($options['condition'])) {
263 1
            $condition = $options['condition'];
264 1
            unset($options['condition']);
265 1
            return self::wrapIntoCondition(static::tag('script', '', $options), $condition);
266
        } else {
267 22
            return static::tag('script', '', $options);
268
        }
269
    }
270
271
    /**
272
     * Wraps given content into conditional comments for IE, e.g., `lt IE 9`.
273
     * @param string $content raw HTML content.
274
     * @param string $condition condition string.
275
     * @return string generated HTML.
276
     */
277 2
    private static function wrapIntoCondition($content, $condition)
278
    {
279 2
        if (strpos($condition, '!IE') !== false) {
280 2
            return "<!--[if $condition]><!-->\n" . $content . "\n<!--<![endif]-->";
281
        }
282 2
        return "<!--[if $condition]>\n" . $content . "\n<![endif]-->";
283
    }
284
285
    /**
286
     * Generates the meta tags containing CSRF token information.
287
     * @return string the generated meta tags
288
     * @see Request::enableCsrfValidation
289
     */
290
    public static function csrfMetaTags()
291
    {
292
        $request = Yii::$app->getRequest();
293
        if ($request instanceof Request && $request->enableCsrfValidation) {
294
            return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n    "
295
                . static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n";
296
        } else {
297
            return '';
298
        }
299
    }
300
301
    /**
302
     * Generates a form start tag.
303
     * @param array|string $action the form action URL. This parameter will be processed by [[Url::to()]].
304
     * @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive).
305
     * Since most browsers only support "post" and "get", if other methods are given, they will
306
     * be simulated using "post", and a hidden input will be added which contains the actual method type.
307
     * See [[\yii\web\Request::methodParam]] for more details.
308
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
309
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
310
     * If a value is null, the corresponding attribute will not be rendered.
311
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
312
     *
313
     * Special options:
314
     *
315
     *  - `csrf`: whether to generate the CSRF hidden input. Defaults to true.
316
     *
317
     * @return string the generated form start tag.
318
     * @see endForm()
319
     */
320 31
    public static function beginForm($action = '', $method = 'post', $options = [])
321
    {
322 31
        $action = Url::to($action);
323
324 31
        $hiddenInputs = [];
325
326 31
        $request = Yii::$app->getRequest();
327 31
        if ($request instanceof Request) {
328 28
            if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) {
329
                // simulate PUT, DELETE, etc. via POST
330
                $hiddenInputs[] = static::hiddenInput($request->methodParam, $method);
331
                $method = 'post';
332
            }
333 28
            $csrf = ArrayHelper::remove($options, 'csrf', true);
334
335 28
            if ($csrf && $request->enableCsrfValidation && strcasecmp($method, 'post') === 0) {
336 27
                $hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken());
337 27
            }
338 28
        }
339
340 31
        if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) {
341
            // query parameters in the action are ignored for GET method
342
            // we use hidden fields to add them back
343 1
            foreach (explode('&', substr($action, $pos + 1)) as $pair) {
344 1
                if (($pos1 = strpos($pair, '=')) !== false) {
345 1
                    $hiddenInputs[] = static::hiddenInput(
346 1
                        urldecode(substr($pair, 0, $pos1)),
347 1
                        urldecode(substr($pair, $pos1 + 1))
348 1
                    );
349 1
                } else {
350
                    $hiddenInputs[] = static::hiddenInput(urldecode($pair), '');
351
                }
352 1
            }
353 1
            $action = substr($action, 0, $pos);
354 1
        }
355
356 31
        $options['action'] = $action;
357 31
        $options['method'] = $method;
358 31
        $form = static::beginTag('form', $options);
359 31
        if (!empty($hiddenInputs)) {
360 28
            $form .= "\n" . implode("\n", $hiddenInputs);
361 28
        }
362
363 31
        return $form;
364
    }
365
366
    /**
367
     * Generates a form end tag.
368
     * @return string the generated tag
369
     * @see beginForm()
370
     */
371 30
    public static function endForm()
372
    {
373 30
        return '</form>';
374
    }
375
376
    /**
377
     * Generates a hyperlink tag.
378
     * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
379
     * such as an image tag. If this is coming from end users, you should consider [[encode()]]
380
     * it to prevent XSS attacks.
381
     * @param array|string|null $url the URL for the hyperlink tag. This parameter will be processed by [[Url::to()]]
382
     * and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute
383
     * will not be generated.
384
     *
385
     * If you want to use an absolute url you can call [[Url::to()]] yourself, before passing the URL to this method,
386
     * like this:
387
     *
388
     * ```php
389
     * Html::a('link text', Url::to($url, true))
390
     * ```
391
     *
392
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
393
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
394
     * If a value is null, the corresponding attribute will not be rendered.
395
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
396
     * @return string the generated hyperlink
397
     * @see \yii\helpers\Url::to()
398
     */
399 13
    public static function a($text, $url = null, $options = [])
400
    {
401 13
        if ($url !== null) {
402 13
            $options['href'] = Url::to($url);
403 13
        }
404 13
        return static::tag('a', $text, $options);
405
    }
406
407
    /**
408
     * Generates a mailto hyperlink.
409
     * @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
410
     * such as an image tag. If this is coming from end users, you should consider [[encode()]]
411
     * it to prevent XSS attacks.
412
     * @param string $email email address. If this is null, the first parameter (link body) will be treated
413
     * as the email address and used.
414
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
415
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
416
     * If a value is null, the corresponding attribute will not be rendered.
417
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
418
     * @return string the generated mailto link
419
     */
420 2
    public static function mailto($text, $email = null, $options = [])
421
    {
422 2
        $options['href'] = 'mailto:' . ($email === null ? $text : $email);
423 2
        return static::tag('a', $text, $options);
424
    }
425
426
    /**
427
     * Generates an image tag.
428
     * @param array|string $src the image URL. This parameter will be processed by [[Url::to()]].
429
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
430
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
431
     * If a value is null, the corresponding attribute will not be rendered.
432
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
433
     * @return string the generated image tag
434
     */
435 2
    public static function img($src, $options = [])
436
    {
437 2
        $options['src'] = Url::to($src);
438 2
        if (!isset($options['alt'])) {
439 2
            $options['alt'] = '';
440 2
        }
441 2
        return static::tag('img', '', $options);
442
    }
443
444
    /**
445
     * Generates a label tag.
446
     * @param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code
447
     * such as an image tag. If this is is coming from end users, you should [[encode()]]
448
     * it to prevent XSS attacks.
449
     * @param string $for the ID of the HTML element that this label is associated with.
450
     * If this is null, the "for" attribute will not be generated.
451
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
452
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
453
     * If a value is null, the corresponding attribute will not be rendered.
454
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
455
     * @return string the generated label tag
456
     */
457 16
    public static function label($content, $for = null, $options = [])
458
    {
459 16
        $options['for'] = $for;
460 16
        return static::tag('label', $content, $options);
461
    }
462
463
    /**
464
     * Generates a button tag.
465
     * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
466
     * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
467
     * you should consider [[encode()]] it to prevent XSS attacks.
468
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
469
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
470
     * If a value is null, the corresponding attribute will not be rendered.
471
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
472
     * @return string the generated button tag
473
     */
474 3
    public static function button($content = 'Button', $options = [])
475
    {
476 3
        if (!isset($options['type'])) {
477 1
            $options['type'] = 'button';
478 1
        }
479 3
        return static::tag('button', $content, $options);
480
    }
481
482
    /**
483
     * Generates a submit button tag.
484
     *
485
     * Be careful when naming form elements such as submit buttons. According to the [jQuery documentation](https://api.jquery.com/submit/) there
486
     * are some reserved names that can cause conflicts, e.g. `submit`, `length`, or `method`.
487
     *
488
     * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
489
     * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
490
     * you should consider [[encode()]] it to prevent XSS attacks.
491
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
492
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
493
     * If a value is null, the corresponding attribute will not be rendered.
494
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
495
     * @return string the generated submit button tag
496
     */
497 1
    public static function submitButton($content = 'Submit', $options = [])
498
    {
499 1
        $options['type'] = 'submit';
500 1
        return static::button($content, $options);
501
    }
502
503
    /**
504
     * Generates a reset button tag.
505
     * @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
506
     * Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
507
     * you should consider [[encode()]] it to prevent XSS attacks.
508
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
509
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
510
     * If a value is null, the corresponding attribute will not be rendered.
511
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
512
     * @return string the generated reset button tag
513
     */
514 1
    public static function resetButton($content = 'Reset', $options = [])
515
    {
516 1
        $options['type'] = 'reset';
517 1
        return static::button($content, $options);
518
    }
519
520
    /**
521
     * Generates an input type of the given type.
522
     * @param string $type the type attribute.
523
     * @param string $name the name attribute. If it is null, the name attribute will not be generated.
524
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
525
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
526
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
527
     * If a value is null, the corresponding attribute will not be rendered.
528
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
529
     * @return string the generated input tag
530
     */
531 50
    public static function input($type, $name = null, $value = null, $options = [])
532
    {
533 50
        if (!isset($options['type'])) {
534 50
            $options['type'] = $type;
535 50
        }
536 50
        $options['name'] = $name;
537 50
        $options['value'] = $value === null ? null : (string) $value;
538 50
        return static::tag('input', '', $options);
539
    }
540
541
    /**
542
     * Generates an input button.
543
     * @param string $label the value attribute. If it is null, the value attribute will not be generated.
544
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
545
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
546
     * If a value is null, the corresponding attribute will not be rendered.
547
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
548
     * @return string the generated button tag
549
     */
550 1
    public static function buttonInput($label = 'Button', $options = [])
551
    {
552 1
        $options['type'] = 'button';
553 1
        $options['value'] = $label;
554 1
        return static::tag('input', '', $options);
555
    }
556
557
    /**
558
     * Generates a submit input button.
559
     *
560
     * Be careful when naming form elements such as submit buttons. According to the [jQuery documentation](https://api.jquery.com/submit/) there
561
     * are some reserved names that can cause conflicts, e.g. `submit`, `length`, or `method`.
562
     *
563
     * @param string $label the value attribute. If it is null, the value attribute will not be generated.
564
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
565
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
566
     * If a value is null, the corresponding attribute will not be rendered.
567
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
568
     * @return string the generated button tag
569
     */
570 1
    public static function submitInput($label = 'Submit', $options = [])
571
    {
572 1
        $options['type'] = 'submit';
573 1
        $options['value'] = $label;
574 1
        return static::tag('input', '', $options);
575
    }
576
577
    /**
578
     * Generates a reset input button.
579
     * @param string $label the value attribute. If it is null, the value attribute will not be generated.
580
     * @param array $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]].
581
     * Attributes whose value is null will be ignored and not put in the tag returned.
582
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
583
     * @return string the generated button tag
584
     */
585 1
    public static function resetInput($label = 'Reset', $options = [])
586
    {
587 1
        $options['type'] = 'reset';
588 1
        $options['value'] = $label;
589 1
        return static::tag('input', '', $options);
590
    }
591
592
    /**
593
     * Generates a text input field.
594
     * @param string $name the name attribute.
595
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
596
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
597
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
598
     * If a value is null, the corresponding attribute will not be rendered.
599
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
600
     * @return string the generated text input tag
601
     */
602 1
    public static function textInput($name, $value = null, $options = [])
603
    {
604 1
        return static::input('text', $name, $value, $options);
605
    }
606
607
    /**
608
     * Generates a hidden input field.
609
     * @param string $name the name attribute.
610
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
611
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
612
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
613
     * If a value is null, the corresponding attribute will not be rendered.
614
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
615
     * @return string the generated hidden input tag
616
     */
617 35
    public static function hiddenInput($name, $value = null, $options = [])
618
    {
619 35
        return static::input('hidden', $name, $value, $options);
620
    }
621
622
    /**
623
     * Generates a password input field.
624
     * @param string $name the name attribute.
625
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
626
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
627
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
628
     * If a value is null, the corresponding attribute will not be rendered.
629
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
630
     * @return string the generated password input tag
631
     */
632 1
    public static function passwordInput($name, $value = null, $options = [])
633
    {
634 1
        return static::input('password', $name, $value, $options);
635
    }
636
637
    /**
638
     * Generates a file input field.
639
     * To use a file input field, you should set the enclosing form's "enctype" attribute to
640
     * be "multipart/form-data". After the form is submitted, the uploaded file information
641
     * can be obtained via $_FILES[$name] (see PHP documentation).
642
     * @param string $name the name attribute.
643
     * @param string $value the value attribute. If it is null, the value attribute will not be generated.
644
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
645
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
646
     * If a value is null, the corresponding attribute will not be rendered.
647
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
648
     * @return string the generated file input tag
649
     */
650 1
    public static function fileInput($name, $value = null, $options = [])
651
    {
652 1
        return static::input('file', $name, $value, $options);
653
    }
654
655
    /**
656
     * Generates a text area input.
657
     * @param string $name the input name
658
     * @param string $value the input value. Note that it will be encoded using [[encode()]].
659
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
660
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
661
     * If a value is null, the corresponding attribute will not be rendered.
662
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
663
     * The following special options are recognized:
664
     *
665
     * - `doubleEncode`: whether to double encode HTML entities in `$value`. If `false`, HTML entities in `$value` will not
666
     * be further encoded. This option is available since version 2.0.11.
667
     *
668
     * @return string the generated text area tag
669
     */
670 8
    public static function textarea($name, $value = '', $options = [])
671
    {
672 8
        $options['name'] = $name;
673 8
        $doubleEncode = ArrayHelper::remove($options, 'doubleEncode', true);
674 8
        return static::tag('textarea', static::encode($value, $doubleEncode), $options);
675
    }
676
677
    /**
678
     * Generates a radio button input.
679
     * @param string $name the name attribute.
680
     * @param bool $checked whether the radio button should be checked.
681
     * @param array $options the tag options in terms of name-value pairs.
682
     * See [[booleanInput()]] for details about accepted attributes.
683
     *
684
     * @return string the generated radio button tag
685
     */
686 2
    public static function radio($name, $checked = false, $options = [])
687
    {
688 2
        return static::booleanInput('radio', $name, $checked, $options);
689
    }
690
691
    /**
692
     * Generates a checkbox input.
693
     * @param string $name the name attribute.
694
     * @param bool $checked whether the checkbox should be checked.
695
     * @param array $options the tag options in terms of name-value pairs.
696
     * See [[booleanInput()]] for details about accepted attributes.
697
     *
698
     * @return string the generated checkbox tag
699
     */
700 4
    public static function checkbox($name, $checked = false, $options = [])
701
    {
702 4
        return static::booleanInput('checkbox', $name, $checked, $options);
703
    }
704
705
    /**
706
     * Generates a boolean input.
707
     * @param string $type the input type. This can be either `radio` or `checkbox`.
708
     * @param string $name the name attribute.
709
     * @param bool $checked whether the checkbox should be checked.
710
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
711
     *
712
     * - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute
713
     *   is present, a hidden input will be generated so that if the checkbox is not checked and is submitted,
714
     *   the value of this attribute will still be submitted to the server via the hidden input.
715
     * - label: string, a label displayed next to the checkbox.  It will NOT be HTML-encoded. Therefore you can pass
716
     *   in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
717
     *   When this option is specified, the checkbox will be enclosed by a label tag.
718
     * - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option.
719
     *
720
     * The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will
721
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
722
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
723
     *
724
     * @return string the generated checkbox tag
725
     * @since 2.0.9
726
     */
727 6
    protected static function booleanInput($type, $name, $checked = false, $options = [])
728
    {
729 6
        $options['checked'] = (bool) $checked;
730 6
        $value = array_key_exists('value', $options) ? $options['value'] : '1';
731 6
        if (isset($options['uncheck'])) {
732
            // add a hidden field so that if the checkbox is not selected, it still submits a value
733 2
            $hidden = static::hiddenInput($name, $options['uncheck']);
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...
734 2
            unset($options['uncheck']);
735 2
        } else {
736 6
            $hidden = '';
737
        }
738 6
        if (isset($options['label'])) {
739 4
            $label = $options['label'];
740 4
            $labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
741 4
            unset($options['label'], $options['labelOptions']);
742 4
            $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 740 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...
743 5
            return $hidden . $content;
744
        } else {
745 6
            return $hidden . static::input($type, $name, $value, $options);
746
        }
747
    }
748
749
    /**
750
     * Generates a drop-down list.
751
     * @param string $name the input name
752
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
753
     * @param array $items the option data items. The array keys are option values, and the array values
754
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
755
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
756
     * If you have a list of data models, you may convert them into the format described above using
757
     * [[\yii\helpers\ArrayHelper::map()]].
758
     *
759
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
760
     * the labels will also be HTML-encoded.
761
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
762
     *
763
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
764
     *   to override the value and to set other tag attributes:
765
     *
766
     *   ```php
767
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
768
     *   ```
769
     *
770
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
771
     *   and the array values are the extra attributes for the corresponding option tags. For example,
772
     *
773
     *   ```php
774
     *   [
775
     *       'value1' => ['disabled' => true],
776
     *       'value2' => ['label' => 'value 2'],
777
     *   ];
778
     *   ```
779
     *
780
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
781
     *   except that the array keys represent the optgroup labels specified in $items.
782
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
783
     *   Defaults to false.
784
     * - encode: bool, whether to encode option prompt and option value characters.
785
     *   Defaults to `true`. This option is available since 2.0.3.
786
     *
787
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
788
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
789
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
790
     *
791
     * @return string the generated drop-down list tag
792
     */
793 2
    public static function dropDownList($name, $selection = null, $items = [], $options = [])
794
    {
795 2
        if (!empty($options['multiple'])) {
796
            return static::listBox($name, $selection, $items, $options);
797
        }
798 2
        $options['name'] = $name;
799 2
        unset($options['unselect']);
800 2
        $selectOptions = static::renderSelectOptions($selection, $items, $options);
801 2
        return static::tag('select', "\n" . $selectOptions . "\n", $options);
802
    }
803
804
    /**
805
     * Generates a list box.
806
     * @param string $name the input name
807
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
808
     * @param array $items the option data items. The array keys are option values, and the array values
809
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
810
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
811
     * If you have a list of data models, you may convert them into the format described above using
812
     * [[\yii\helpers\ArrayHelper::map()]].
813
     *
814
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
815
     * the labels will also be HTML-encoded.
816
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
817
     *
818
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
819
     *   to override the value and to set other tag attributes:
820
     *
821
     *   ```php
822
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
823
     *   ```
824
     *
825
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
826
     *   and the array values are the extra attributes for the corresponding option tags. For example,
827
     *
828
     *   ```php
829
     *   [
830
     *       'value1' => ['disabled' => true],
831
     *       'value2' => ['label' => 'value 2'],
832
     *   ];
833
     *   ```
834
     *
835
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
836
     *   except that the array keys represent the optgroup labels specified in $items.
837
     * - unselect: string, the value that will be submitted when no option is selected.
838
     *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
839
     *   mode, we can still obtain the posted unselect value.
840
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
841
     *   Defaults to false.
842
     * - encode: bool, whether to encode option prompt and option value characters.
843
     *   Defaults to `true`. This option is available since 2.0.3.
844
     *
845
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
846
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
847
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
848
     *
849
     * @return string the generated list box tag
850
     */
851 3
    public static function listBox($name, $selection = null, $items = [], $options = [])
852
    {
853 3
        if (!array_key_exists('size', $options)) {
854 3
            $options['size'] = 4;
855 3
        }
856 3
        if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) {
857 2
            $name .= '[]';
858 2
        }
859 3
        $options['name'] = $name;
860 3
        if (isset($options['unselect'])) {
861
            // add a hidden field so that if the list box has no option being selected, it still submits a value
862 3
            if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) {
863 1
                $name = substr($name, 0, -2);
864 1
            }
865 3
            $hidden = static::hiddenInput($name, $options['unselect']);
866 3
            unset($options['unselect']);
867 3
        } else {
868 1
            $hidden = '';
869
        }
870 3
        $selectOptions = static::renderSelectOptions($selection, $items, $options);
871 3
        return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
872
    }
873
874
    /**
875
     * Generates a list of checkboxes.
876
     * A checkbox list allows multiple selection, like [[listBox()]].
877
     * As a result, the corresponding submitted value is an array.
878
     * @param string $name the name attribute of each checkbox.
879
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
880
     * @param array $items the data item used to generate the checkboxes.
881
     * The array keys are the checkbox values, while the array values are the corresponding labels.
882
     * @param array $options options (name => config) for the checkbox list container tag.
883
     * The following options are specially handled:
884
     *
885
     * - tag: string|false, the tag name of the container element. False to render checkbox without container.
886
     *   See also [[tag()]].
887
     * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
888
     *   By setting this option, a hidden input will be generated.
889
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
890
     *   This option is ignored if `item` option is set.
891
     * - separator: string, the HTML code that separates items.
892
     * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
893
     * - item: callable, a callback that can be used to customize the generation of the HTML code
894
     *   corresponding to a single item in $items. The signature of this callback must be:
895
     *
896
     *   ```php
897
     *   function ($index, $label, $name, $checked, $value)
898
     *   ```
899
     *
900
     *   where $index is the zero-based index of the checkbox in the whole list; $label
901
     *   is the label for the checkbox; and $name, $value and $checked represent the name,
902
     *   value and the checked status of the checkbox input, respectively.
903
     *
904
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
905
     *
906
     * @return string the generated checkbox list
907
     */
908 1
    public static function checkboxList($name, $selection = null, $items = [], $options = [])
909
    {
910 1
        if (substr($name, -2) !== '[]') {
911 1
            $name .= '[]';
912 1
        }
913
914 1
        $formatter = ArrayHelper::remove($options, 'item');
915 1
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
916 1
        $encode = ArrayHelper::remove($options, 'encode', true);
917 1
        $separator = ArrayHelper::remove($options, 'separator', "\n");
918 1
        $tag = ArrayHelper::remove($options, 'tag', 'div');
919
920 1
        $lines = [];
921 1
        $index = 0;
922 1
        foreach ($items as $value => $label) {
923 1
            $checked = $selection !== null &&
924 1
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
925 1
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn($value, $selection));
0 ignored issues
show
Bug introduced by
It seems like $selection defined by parameter $selection on line 908 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...
926 1
            if ($formatter !== null) {
927 1
                $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
928 1
            } else {
929 1
                $lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [
930 1
                    'value' => $value,
931 1
                    'label' => $encode ? static::encode($label) : $label,
932 1
                ]));
933
            }
934 1
            $index++;
935 1
        }
936
937 1
        if (isset($options['unselect'])) {
938
            // add a hidden field so that if the list box has no option being selected, it still submits a value
939 1
            $name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
940 1
            $hidden = static::hiddenInput($name2, $options['unselect']);
941 1
            unset($options['unselect']);
942 1
        } else {
943 1
            $hidden = '';
944
        }
945
946 1
        $visibleContent = implode($separator, $lines);
947
948 1
        if ($tag === false) {
949 1
            return $hidden . $visibleContent;
950
        }
951
952 1
        return $hidden . static::tag($tag, $visibleContent, $options);
953
    }
954
955
    /**
956
     * Generates a list of radio buttons.
957
     * A radio button list is like a checkbox list, except that it only allows single selection.
958
     * @param string $name the name attribute of each radio button.
959
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
960
     * @param array $items the data item used to generate the radio buttons.
961
     * The array keys are the radio button values, while the array values are the corresponding labels.
962
     * @param array $options options (name => config) for the radio button list container tag.
963
     * The following options are specially handled:
964
     *
965
     * - tag: string|false, the tag name of the container element. False to render radio buttons without container.
966
     *   See also [[tag()]].
967
     * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
968
     *   By setting this option, a hidden input will be generated.
969
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
970
     *   This option is ignored if `item` option is set.
971
     * - separator: string, the HTML code that separates items.
972
     * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
973
     * - item: callable, a callback that can be used to customize the generation of the HTML code
974
     *   corresponding to a single item in $items. The signature of this callback must be:
975
     *
976
     *   ```php
977
     *   function ($index, $label, $name, $checked, $value)
978
     *   ```
979
     *
980
     *   where $index is the zero-based index of the radio button in the whole list; $label
981
     *   is the label for the radio button; and $name, $value and $checked represent the name,
982
     *   value and the checked status of the radio button input, respectively.
983
     *
984
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
985
     *
986
     * @return string the generated radio button list
987
     */
988 1
    public static function radioList($name, $selection = null, $items = [], $options = [])
989
    {
990 1
        $formatter = ArrayHelper::remove($options, 'item');
991 1
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
992 1
        $encode = ArrayHelper::remove($options, 'encode', true);
993 1
        $separator = ArrayHelper::remove($options, 'separator', "\n");
994 1
        $tag = ArrayHelper::remove($options, 'tag', 'div');
995
        // add a hidden field so that if the list box has no option being selected, it still submits a value
996 1
        $hidden = isset($options['unselect']) ? static::hiddenInput($name, $options['unselect']) : '';
997 1
        unset($options['unselect']);
998
999 1
        $lines = [];
1000 1
        $index = 0;
1001 1
        foreach ($items as $value => $label) {
1002 1
            $checked = $selection !== null &&
1003 1
                (!ArrayHelper::isTraversable($selection) && !strcmp($value, $selection)
1004 1
                    || ArrayHelper::isTraversable($selection) && ArrayHelper::isIn($value, $selection));
0 ignored issues
show
Bug introduced by
It seems like $selection defined by parameter $selection on line 988 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...
1005 1
            if ($formatter !== null) {
1006 1
                $lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
1007 1
            } else {
1008 1
                $lines[] = static::radio($name, $checked, array_merge($itemOptions, [
1009 1
                    'value' => $value,
1010 1
                    'label' => $encode ? static::encode($label) : $label,
1011 1
                ]));
1012
            }
1013 1
            $index++;
1014 1
        }
1015 1
        $visibleContent = implode($separator, $lines);
1016
1017 1
        if ($tag === false) {
1018 1
            return $hidden . $visibleContent;
1019
        }
1020
1021 1
        return $hidden . static::tag($tag, $visibleContent, $options);
1022
    }
1023
1024
    /**
1025
     * Generates an unordered list.
1026
     * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
1027
     * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
1028
     * @param array $options options (name => config) for the radio button list. The following options are supported:
1029
     *
1030
     * - encode: boolean, whether to HTML-encode the items. Defaults to true.
1031
     *   This option is ignored if the `item` option is specified.
1032
     * - separator: string, the HTML code that separates items. Defaults to a simple newline (`"\n"`).
1033
     *   This option is available since version 2.0.7.
1034
     * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
1035
     * - item: callable, a callback that is used to generate each individual list item.
1036
     *   The signature of this callback must be:
1037
     *
1038
     *   ```php
1039
     *   function ($item, $index)
1040
     *   ```
1041
     *
1042
     *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
1043
     *   the whole list item tag.
1044
     *
1045
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1046
     *
1047
     * @return string the generated unordered list. An empty list tag will be returned if `$items` is empty.
1048
     */
1049 4
    public static function ul($items, $options = [])
1050
    {
1051 4
        $tag = ArrayHelper::remove($options, 'tag', 'ul');
1052 4
        $encode = ArrayHelper::remove($options, 'encode', true);
1053 4
        $formatter = ArrayHelper::remove($options, 'item');
1054 4
        $separator = ArrayHelper::remove($options, 'separator', "\n");
1055 4
        $itemOptions = ArrayHelper::remove($options, 'itemOptions', []);
1056
1057 4
        if (empty($items)) {
1058 2
            return static::tag($tag, '', $options);
1059
        }
1060
1061 4
        $results = [];
1062 4
        foreach ($items as $index => $item) {
1063 4
            if ($formatter !== null) {
1064 2
                $results[] = call_user_func($formatter, $item, $index);
1065 2
            } else {
1066 4
                $results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
1067
            }
1068 4
        }
1069
1070 4
        return static::tag(
1071 4
            $tag,
1072 4
            $separator . implode($separator, $results) . $separator,
1073
            $options
1074 4
        );
1075
    }
1076
1077
    /**
1078
     * Generates an ordered list.
1079
     * @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
1080
     * Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
1081
     * @param array $options options (name => config) for the radio button list. The following options are supported:
1082
     *
1083
     * - encode: boolean, whether to HTML-encode the items. Defaults to true.
1084
     *   This option is ignored if the `item` option is specified.
1085
     * - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
1086
     * - item: callable, a callback that is used to generate each individual list item.
1087
     *   The signature of this callback must be:
1088
     *
1089
     *   ```php
1090
     *   function ($item, $index)
1091
     *   ```
1092
     *
1093
     *   where $index is the array key corresponding to `$item` in `$items`. The callback should return
1094
     *   the whole list item tag.
1095
     *
1096
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1097
     *
1098
     * @return string the generated ordered list. An empty string is returned if `$items` is empty.
1099
     */
1100 1
    public static function ol($items, $options = [])
1101
    {
1102 1
        $options['tag'] = 'ol';
1103 1
        return static::ul($items, $options);
1104
    }
1105
1106
    /**
1107
     * Generates a label tag for the given model attribute.
1108
     * The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
1109
     * @param Model $model the model object
1110
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1111
     * about attribute expression.
1112
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1113
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1114
     * If a value is null, the corresponding attribute will not be rendered.
1115
     * The following options are specially handled:
1116
     *
1117
     * - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
1118
     *   If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
1119
     *   (after encoding).
1120
     *
1121
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1122
     *
1123
     * @return string the generated label tag
1124
     */
1125 11
    public static function activeLabel($model, $attribute, $options = [])
1126
    {
1127 11
        $for = ArrayHelper::remove($options, 'for', static::getInputId($model, $attribute));
1128 11
        $attribute = static::getAttributeName($attribute);
1129 11
        $label = ArrayHelper::remove($options, 'label', static::encode($model->getAttributeLabel($attribute)));
1130 11
        return static::label($label, $for, $options);
1131
    }
1132
1133
    /**
1134
     * Generates a hint tag for the given model attribute.
1135
     * The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]].
1136
     * If no hint content can be obtained, method will return an empty string.
1137
     * @param Model $model the model object
1138
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1139
     * about attribute expression.
1140
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1141
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1142
     * If a value is null, the corresponding attribute will not be rendered.
1143
     * The following options are specially handled:
1144
     *
1145
     * - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]].
1146
     *   If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display
1147
     *   (without encoding).
1148
     *
1149
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1150
     *
1151
     * @return string the generated hint tag
1152
     * @since 2.0.4
1153
     */
1154 11
    public static function activeHint($model, $attribute, $options = [])
1155
    {
1156 11
        $attribute = static::getAttributeName($attribute);
1157 11
        $hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute);
1158 11
        if (empty($hint)) {
1159 3
            return '';
1160
        }
1161 8
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1162 8
        unset($options['hint']);
1163 8
        return static::tag($tag, $hint, $options);
1164
    }
1165
1166
    /**
1167
     * Generates a summary of the validation errors.
1168
     * If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
1169
     * @param Model|Model[] $models the model(s) whose validation errors are to be displayed.
1170
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1171
     *
1172
     * - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
1173
     * - footer: string, the footer HTML for the error summary. Defaults to empty string.
1174
     * - encode: boolean, if set to false then the error messages won't be encoded. Defaults to `true`.
1175
     * - showAllErrors: boolean, if set to true every error message for each attribute will be shown otherwise
1176
     *   only the first error message for each attribute will be shown. Defaults to `false`.
1177
     *   Option is available since 2.0.10.
1178
     *
1179
     * The rest of the options will be rendered as the attributes of the container tag.
1180
     *
1181
     * @return string the generated error summary
1182
     */
1183 7
    public static function errorSummary($models, $options = [])
1184
    {
1185 7
        $header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
1186 7
        $footer = ArrayHelper::remove($options, 'footer', '');
1187 7
        $encode = ArrayHelper::remove($options, 'encode', true);
1188 7
        $showAllErrors = ArrayHelper::remove($options, 'showAllErrors', false);
1189 7
        unset($options['header']);
1190
1191 7
        $lines = [];
1192 7
        if (!is_array($models)) {
1193 7
            $models = [$models];
1194 7
        }
1195 7
        foreach ($models as $model) {
1196
            /* @var $model Model */
1197 7
            foreach ($model->getErrors() as $errors) {
1198 5
                foreach ($errors as $error) {
1199 5
                    $line = $encode ? Html::encode($error) : $error;
1200 5
                    if (array_search($line, $lines) === false) {
1201 5
                        $lines[] = $line;
1202 5
                    }
1203 5
                    if (!$showAllErrors) {
1204 4
                        break;
1205
                    }
1206 5
                }
1207 7
            }
1208 7
        }
1209
1210 7
        if (empty($lines)) {
1211
            // still render the placeholder for client-side validation use
1212 2
            $content = '<ul></ul>';
1213 2
            $options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
1214 2
        } else {
1215 5
            $content = '<ul><li>' . implode("</li>\n<li>", $lines) . '</li></ul>';
1216
        }
1217 7
        return Html::tag('div', $header . $content . $footer, $options);
1218
    }
1219
1220
    /**
1221
     * Generates a tag that contains the first validation error of the specified model attribute.
1222
     * Note that even if there is no validation error, this method will still return an empty error tag.
1223
     * @param Model $model the model object
1224
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1225
     * about attribute expression.
1226
     * @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
1227
     * using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1228
     *
1229
     * The following options are specially handled:
1230
     *
1231
     * - tag: this specifies the tag name. If not set, "div" will be used.
1232
     *   See also [[tag()]].
1233
     * - encode: boolean, if set to false then the error message won't be encoded.
1234
     *
1235
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1236
     *
1237
     * @return string the generated label tag
1238
     */
1239 9
    public static function error($model, $attribute, $options = [])
1240
    {
1241 9
        $attribute = static::getAttributeName($attribute);
1242 9
        $error = $model->getFirstError($attribute);
1243 9
        $tag = ArrayHelper::remove($options, 'tag', 'div');
1244 9
        $encode = ArrayHelper::remove($options, 'encode', true);
1245 9
        return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
1246
    }
1247
1248
    /**
1249
     * Generates an input tag for the given model attribute.
1250
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1251
     * unless they are explicitly specified in `$options`.
1252
     * @param string $type the input type (e.g. 'text', 'password')
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. These will be rendered as
1257
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1258
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1259
     * @return string the generated input tag
1260
     */
1261 19
    public static function activeInput($type, $model, $attribute, $options = [])
1262
    {
1263 19
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1264 19
        $value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1265 19
        if (!array_key_exists('id', $options)) {
1266 17
            $options['id'] = static::getInputId($model, $attribute);
1267 17
        }
1268 19
        return static::input($type, $name, $value, $options);
1269
    }
1270
1271
    /**
1272
     * If `maxlength` option is set true and the model attribute is validated by a string validator,
1273
     * the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1274
     * @param Model $model the model object
1275
     * @param string $attribute the attribute name or expression.
1276
     * @param array $options the tag options in terms of name-value pairs.
1277
     */
1278 19
    private static function normalizeMaxLength($model, $attribute, &$options)
1279
    {
1280 19
        if (isset($options['maxlength']) && $options['maxlength'] === true) {
1281 3
            unset($options['maxlength']);
1282 3
            $attrName = static::getAttributeName($attribute);
1283 3
            foreach ($model->getActiveValidators($attrName) as $validator) {
1284 3
                if ($validator instanceof StringValidator && $validator->max !== null) {
1285 3
                    $options['maxlength'] = $validator->max;
1286 3
                    break;
1287
                }
1288 3
            }
1289 3
        }
1290 19
    }
1291
1292
    /**
1293
     * Generates a text input tag for the given model attribute.
1294
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1295
     * unless they are explicitly specified in `$options`.
1296
     * @param Model $model the model object
1297
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1298
     * about attribute expression.
1299
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1300
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1301
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1302
     * The following special options are recognized:
1303
     *
1304
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1305
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1306
     *   This is available since version 2.0.3.
1307
     *
1308
     * @return string the generated input tag
1309
     */
1310 12
    public static function activeTextInput($model, $attribute, $options = [])
1311
    {
1312 12
        self::normalizeMaxLength($model, $attribute, $options);
1313 12
        return static::activeInput('text', $model, $attribute, $options);
1314
    }
1315
1316
    /**
1317
     * Generates a hidden input tag for the given model attribute.
1318
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1319
     * unless they are explicitly specified in `$options`.
1320
     * @param Model $model the model object
1321
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1322
     * about attribute expression.
1323
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1324
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1325
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1326
     * @return string the generated input tag
1327
     */
1328 2
    public static function activeHiddenInput($model, $attribute, $options = [])
1329
    {
1330 2
        return static::activeInput('hidden', $model, $attribute, $options);
1331
    }
1332
1333
    /**
1334
     * Generates a password input tag for the given model attribute.
1335
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1336
     * unless they are explicitly specified in `$options`.
1337
     * @param Model $model the model object
1338
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1339
     * about attribute expression.
1340
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1341
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1342
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1343
     * The following special options are recognized:
1344
     *
1345
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1346
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1347
     *   This option is available since version 2.0.6.
1348
     *
1349
     * @return string the generated input tag
1350
     */
1351 3
    public static function activePasswordInput($model, $attribute, $options = [])
1352
    {
1353 3
        self::normalizeMaxLength($model, $attribute, $options);
1354 3
        return static::activeInput('password', $model, $attribute, $options);
1355
    }
1356
1357
    /**
1358
     * Generates a file input tag for the given model attribute.
1359
     * This method will generate the "name" and "value" tag attributes automatically for the model attribute
1360
     * unless they are explicitly specified in `$options`.
1361
     * @param Model $model the model object
1362
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1363
     * about attribute expression.
1364
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1365
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1366
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1367
     * @return string the generated input tag
1368
     */
1369 1
    public static function activeFileInput($model, $attribute, $options = [])
1370
    {
1371
        // add a hidden field so that if a model only has a file field, we can
1372
        // still use isset($_POST[$modelClass]) to detect if the input is submitted
1373 1
        $hiddenOptions = ['id' => null, 'value' => ''];
1374 1
        if (isset($options['name'])) {
1375
            $hiddenOptions['name'] = $options['name'];
1376
        }
1377 1
        return static::activeHiddenInput($model, $attribute, $hiddenOptions)
1378 1
            . static::activeInput('file', $model, $attribute, $options);
1379
    }
1380
1381
    /**
1382
     * Generates a textarea tag for the given model attribute.
1383
     * The model attribute value will be used as the content in the textarea.
1384
     * @param Model $model the model object
1385
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1386
     * about attribute expression.
1387
     * @param array $options the tag options in terms of name-value pairs. These will be rendered as
1388
     * the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
1389
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1390
     * The following special options are recognized:
1391
     *
1392
     * - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
1393
     *   by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
1394
     *   This option is available since version 2.0.6.
1395
     *
1396
     * @return string the generated textarea tag
1397
     */
1398 4
    public static function activeTextarea($model, $attribute, $options = [])
1399
    {
1400 4
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1401 4
        if (isset($options['value'])) {
1402 1
            $value = $options['value'];
1403 1
            unset($options['value']);
1404 1
        } else {
1405 3
            $value = static::getAttributeValue($model, $attribute);
1406
        }
1407 4
        if (!array_key_exists('id', $options)) {
1408 4
            $options['id'] = static::getInputId($model, $attribute);
1409 4
        }
1410 4
        self::normalizeMaxLength($model, $attribute, $options);
1411 4
        return static::textarea($name, $value, $options);
1412
    }
1413
1414
    /**
1415
     * Generates a radio button tag together with a label for the given model attribute.
1416
     * This method will generate the "checked" tag attribute according to the model attribute value.
1417
     * @param Model $model the model object
1418
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1419
     * about attribute expression.
1420
     * @param array $options the tag options in terms of name-value pairs.
1421
     * See [[booleanInput()]] for details about accepted attributes.
1422
     *
1423
     * @return string the generated radio button tag
1424
     */
1425
    public static function activeRadio($model, $attribute, $options = [])
1426
    {
1427
        return static::activeBooleanInput('radio', $model, $attribute, $options);
1428
    }
1429
1430
    /**
1431
     * Generates a checkbox tag together with a label for the given model attribute.
1432
     * This method will generate the "checked" tag attribute according to the model attribute value.
1433
     * @param Model $model the model object
1434
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1435
     * about attribute expression.
1436
     * @param array $options the tag options in terms of name-value pairs.
1437
     * See [[booleanInput()]] for details about accepted attributes.
1438
     *
1439
     * @return string the generated checkbox tag
1440
     */
1441
    public static function activeCheckbox($model, $attribute, $options = [])
1442
    {
1443
        return static::activeBooleanInput('checkbox', $model, $attribute, $options);
1444
    }
1445
1446
    /**
1447
     * Generates a boolean input
1448
     * This method is mainly called by [[activeCheckbox()]] and [[activeRadio()]].
1449
     * @param string $type the input type. This can be either `radio` or `checkbox`.
1450
     * @param Model $model the model object
1451
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1452
     * about attribute expression.
1453
     * @param array $options the tag options in terms of name-value pairs.
1454
     * See [[booleanInput()]] for details about accepted attributes.
1455
     * @return string the generated input element
1456
     * @since 2.0.9
1457
     */
1458
    protected static function activeBooleanInput($type, $model, $attribute, $options = [])
1459
    {
1460
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1461
        $value = static::getAttributeValue($model, $attribute);
1462
1463
        if (!array_key_exists('value', $options)) {
1464
            $options['value'] = '1';
1465
        }
1466
        if (!array_key_exists('uncheck', $options)) {
1467
            $options['uncheck'] = '0';
1468
        }
1469
        if (!array_key_exists('label', $options)) {
1470
            $options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
1471
        }
1472
1473
        $checked = "$value" === "{$options['value']}";
1474
1475
        if (!array_key_exists('id', $options)) {
1476
            $options['id'] = static::getInputId($model, $attribute);
1477
        }
1478
1479
        return static::$type($name, $checked, $options);
1480
    }
1481
1482
    /**
1483
     * Generates a drop-down list for the given model attribute.
1484
     * The selection of the drop-down list is taken from the value of the model attribute.
1485
     * @param Model $model the model object
1486
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1487
     * about attribute expression.
1488
     * @param array $items the option data items. The array keys are option values, and the array values
1489
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1490
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1491
     * If you have a list of data models, you may convert them into the format described above using
1492
     * [[\yii\helpers\ArrayHelper::map()]].
1493
     *
1494
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1495
     * the labels will also be HTML-encoded.
1496
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1497
     *
1498
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1499
     *   to override the value and to set other tag attributes:
1500
     *
1501
     *   ```php
1502
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1503
     *   ```
1504
     *
1505
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1506
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1507
     *
1508
     *   ```php
1509
     *   [
1510
     *       'value1' => ['disabled' => true],
1511
     *       'value2' => ['label' => 'value 2'],
1512
     *   ];
1513
     *   ```
1514
     *
1515
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1516
     *   except that the array keys represent the optgroup labels specified in $items.
1517
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1518
     *   Defaults to false.
1519
     * - encode: bool, whether to encode option prompt and option value characters.
1520
     *   Defaults to `true`. This option is available since 2.0.3.
1521
     *
1522
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1523
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1524
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1525
     *
1526
     * @return string the generated drop-down list tag
1527
     */
1528 1
    public static function activeDropDownList($model, $attribute, $items, $options = [])
1529
    {
1530 1
        if (empty($options['multiple'])) {
1531 1
            return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
1532
        } else {
1533
            return static::activeListBox($model, $attribute, $items, $options);
1534
        }
1535
    }
1536
1537
    /**
1538
     * Generates a list box.
1539
     * The selection of the list box is taken from the value of the model attribute.
1540
     * @param Model $model the model object
1541
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1542
     * about attribute expression.
1543
     * @param array $items the option data items. The array keys are option values, and the array values
1544
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1545
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1546
     * If you have a list of data models, you may convert them into the format described above using
1547
     * [[\yii\helpers\ArrayHelper::map()]].
1548
     *
1549
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1550
     * the labels will also be HTML-encoded.
1551
     * @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
1552
     *
1553
     * - prompt: string, a prompt text to be displayed as the first option. Since version 2.0.11 you can use an array
1554
     *   to override the value and to set other tag attributes:
1555
     *
1556
     *   ```php
1557
     *   ['text' => 'Please select', 'options' => ['value' => 'none', 'class' => 'prompt', 'label' => 'Select']],
1558
     *   ```
1559
     *
1560
     * - options: array, the attributes for the select option tags. The array keys must be valid option values,
1561
     *   and the array values are the extra attributes for the corresponding option tags. For example,
1562
     *
1563
     *   ```php
1564
     *   [
1565
     *       'value1' => ['disabled' => true],
1566
     *       'value2' => ['label' => 'value 2'],
1567
     *   ];
1568
     *   ```
1569
     *
1570
     * - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
1571
     *   except that the array keys represent the optgroup labels specified in $items.
1572
     * - unselect: string, the value that will be submitted when no option is selected.
1573
     *   When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
1574
     *   mode, we can still obtain the posted unselect value.
1575
     * - encodeSpaces: bool, whether to encode spaces in option prompt and option value with `&nbsp;` character.
1576
     *   Defaults to false.
1577
     * - encode: bool, whether to encode option prompt and option value characters.
1578
     *   Defaults to `true`. This option is available since 2.0.3.
1579
     *
1580
     * The rest of the options will be rendered as the attributes of the resulting tag. The values will
1581
     * be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
1582
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1583
     *
1584
     * @return string the generated list box tag
1585
     */
1586 2
    public static function activeListBox($model, $attribute, $items, $options = [])
1587
    {
1588 2
        return static::activeListInput('listBox', $model, $attribute, $items, $options);
1589
    }
1590
1591
    /**
1592
     * Generates a list of checkboxes.
1593
     * A checkbox list allows multiple selection, like [[listBox()]].
1594
     * As a result, the corresponding submitted value is an array.
1595
     * The selection of the checkbox list is taken from the value of the model attribute.
1596
     * @param Model $model the model object
1597
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1598
     * about attribute expression.
1599
     * @param array $items the data item used to generate the checkboxes.
1600
     * The array keys are the checkbox values, and the array values are the corresponding labels.
1601
     * Note that the labels will NOT be HTML-encoded, while the values will.
1602
     * @param array $options options (name => config) for the checkbox list container tag.
1603
     * The following options are specially handled:
1604
     *
1605
     * - tag: string|false, the tag name of the container element. False to render checkbox without container.
1606
     *   See also [[tag()]].
1607
     * - unselect: string, the value that should be submitted when none of the checkboxes is selected.
1608
     *   You may set this option to be null to prevent default value submission.
1609
     *   If this option is not set, an empty string will be submitted.
1610
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1611
     *   This option is ignored if `item` option is set.
1612
     * - separator: string, the HTML code that separates items.
1613
     * - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
1614
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1615
     *   corresponding to a single item in $items. The signature of this callback must be:
1616
     *
1617
     *   ```php
1618
     *   function ($index, $label, $name, $checked, $value)
1619
     *   ```
1620
     *
1621
     *   where $index is the zero-based index of the checkbox in the whole list; $label
1622
     *   is the label for the checkbox; and $name, $value and $checked represent the name,
1623
     *   value and the checked status of the checkbox input.
1624
     *
1625
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1626
     *
1627
     * @return string the generated checkbox list
1628
     */
1629
    public static function activeCheckboxList($model, $attribute, $items, $options = [])
1630
    {
1631
        return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
1632
    }
1633
1634
    /**
1635
     * Generates a list of radio buttons.
1636
     * A radio button list is like a checkbox list, except that it only allows single selection.
1637
     * The selection of the radio buttons is taken from the value of the model attribute.
1638
     * @param Model $model the model object
1639
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1640
     * about attribute expression.
1641
     * @param array $items the data item used to generate the radio buttons.
1642
     * The array keys are the radio values, and the array values are the corresponding labels.
1643
     * Note that the labels will NOT be HTML-encoded, while the values will.
1644
     * @param array $options options (name => config) for the radio button list container tag.
1645
     * The following options are specially handled:
1646
     *
1647
     * - tag: string|false, the tag name of the container element. False to render radio button without container.
1648
     *   See also [[tag()]].
1649
     * - unselect: string, the value that should be submitted when none of the radio buttons is selected.
1650
     *   You may set this option to be null to prevent default value submission.
1651
     *   If this option is not set, an empty string will be submitted.
1652
     * - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
1653
     *   This option is ignored if `item` option is set.
1654
     * - separator: string, the HTML code that separates items.
1655
     * - itemOptions: array, the options for generating the radio button tag using [[radio()]].
1656
     * - item: callable, a callback that can be used to customize the generation of the HTML code
1657
     *   corresponding to a single item in $items. The signature of this callback must be:
1658
     *
1659
     *   ```php
1660
     *   function ($index, $label, $name, $checked, $value)
1661
     *   ```
1662
     *
1663
     *   where $index is the zero-based index of the radio button in the whole list; $label
1664
     *   is the label for the radio button; and $name, $value and $checked represent the name,
1665
     *   value and the checked status of the radio button input.
1666
     *
1667
     * See [[renderTagAttributes()]] for details on how attributes are being rendered.
1668
     *
1669
     * @return string the generated radio button list
1670
     */
1671
    public static function activeRadioList($model, $attribute, $items, $options = [])
1672
    {
1673
        return static::activeListInput('radioList', $model, $attribute, $items, $options);
1674
    }
1675
1676
    /**
1677
     * Generates a list of input fields.
1678
     * This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckboxList()]].
1679
     * @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'.
1680
     * @param Model $model the model object
1681
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
1682
     * about attribute expression.
1683
     * @param array $items the data item used to generate the input fields.
1684
     * The array keys are the input values, and the array values are the corresponding labels.
1685
     * Note that the labels will NOT be HTML-encoded, while the values will.
1686
     * @param array $options options (name => config) for the input list. The supported special options
1687
     * depend on the input type specified by `$type`.
1688
     * @return string the generated input list
1689
     */
1690 3
    protected static function activeListInput($type, $model, $attribute, $items, $options = [])
1691
    {
1692 3
        $name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
1693 3
        $selection = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
1694 3
        if (!array_key_exists('unselect', $options)) {
1695 3
            $options['unselect'] = '';
1696 3
        }
1697 3
        if (!array_key_exists('id', $options)) {
1698 2
            $options['id'] = static::getInputId($model, $attribute);
1699 2
        }
1700 3
        return static::$type($name, $selection, $items, $options);
1701
    }
1702
1703
    /**
1704
     * Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
1705
     * @param string|array|null $selection the selected value(s). String for single or array for multiple selection(s).
1706
     * @param array $items the option data items. The array keys are option values, and the array values
1707
     * are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
1708
     * For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
1709
     * If you have a list of data models, you may convert them into the format described above using
1710
     * [[\yii\helpers\ArrayHelper::map()]].
1711
     *
1712
     * Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
1713
     * the labels will also be HTML-encoded.
1714
     * @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
1715
     * This method will take out these elements, if any: "prompt", "options" and "groups". See more details
1716
     * in [[dropDownList()]] for the explanation of these elements.
1717
     *
1718
     * @return string the generated list options
1719
     */
1720 6
    public static function renderSelectOptions($selection, $items, &$tagOptions = [])
1721
    {
1722 6
        $lines = [];
1723 6
        $encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
1724 6
        $encode = ArrayHelper::remove($tagOptions, 'encode', true);
1725 6
        if (isset($tagOptions['prompt'])) {
1726 2
            $promptOptions = ['value' => ''];
1727 2
            if (is_string($tagOptions['prompt'])) {
1728 2
                $promptText = $tagOptions['prompt'];
1729 2
            } else {
1730 1
                $promptText = $tagOptions['prompt']['text'];
1731 1
                $promptOptions = array_merge($promptOptions, $tagOptions['prompt']['options']);
1732
            }
1733 2
            $promptText = $encode ? static::encode($promptText) : $promptText;
1734 2
            if ($encodeSpaces) {
1735 1
                $promptText = str_replace(' ', '&nbsp;', $promptText);
1736 1
            }
1737 2
            $lines[] = static::tag('option', $promptText, $promptOptions);
1738 2
        }
1739
1740 6
        $options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
1741 6
        $groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
1742 6
        unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
1743 6
        $options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
1744 6
        $options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
1745
1746 6
        foreach ($items as $key => $value) {
1747 6
            if (is_array($value)) {
1748 1
                $groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
1749 1
                if (!isset($groupAttrs['label'])) {
1750 1
                    $groupAttrs['label'] = $key;
1751 1
                }
1752 1
                $attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
1753 1
                $content = static::renderSelectOptions($selection, $value, $attrs);
1754 1
                $lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
1755 1
            } else {
1756 6
                $attrs = isset($options[$key]) ? $options[$key] : [];
1757 6
                $attrs['value'] = (string) $key;
1758 6
                if (!array_key_exists('selected', $attrs)) {
1759 6
                    $attrs['selected'] = $selection !== null &&
1760 5
                        (!ArrayHelper::isTraversable($selection) && !strcmp($key, $selection)
1761 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 1720 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...
1762 6
                }
1763 6
                $text = $encode ? static::encode($value) : $value;
1764 6
                if ($encodeSpaces) {
1765 2
                    $text = str_replace(' ', '&nbsp;', $text);
1766 2
                }
1767 6
                $lines[] = static::tag('option', $text, $attrs);
1768
            }
1769 6
        }
1770
1771 6
        return implode("\n", $lines);
1772
    }
1773
1774
    /**
1775
     * Renders the HTML tag attributes.
1776
     *
1777
     * Attributes whose values are of boolean type will be treated as
1778
     * [boolean attributes](http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes).
1779
     *
1780
     * Attributes whose values are null will not be rendered.
1781
     *
1782
     * The values of attributes will be HTML-encoded using [[encode()]].
1783
     *
1784
     * The "data" attribute is specially handled when it is receiving an array value. In this case,
1785
     * the array will be "expanded" and a list data attributes will be rendered. For example,
1786
     * if `'data' => ['id' => 1, 'name' => 'yii']`, then this will be rendered:
1787
     * `data-id="1" data-name="yii"`.
1788
     * Additionally `'data' => ['params' => ['id' => 1, 'name' => 'yii'], 'status' => 'ok']` will be rendered as:
1789
     * `data-params='{"id":1,"name":"yii"}' data-status="ok"`.
1790
     *
1791
     * @param array $attributes attributes to be rendered. The attribute values will be HTML-encoded using [[encode()]].
1792
     * @return string the rendering result. If the attributes are not empty, they will be rendered
1793
     * into a string with a leading white space (so that it can be directly appended to the tag name
1794
     * in a tag. If there is no attribute, an empty string will be returned.
1795
     */
1796 150
    public static function renderTagAttributes($attributes)
1797
    {
1798 150
        if (count($attributes) > 1) {
1799 108
            $sorted = [];
1800 108
            foreach (static::$attributeOrder as $name) {
1801 108
                if (isset($attributes[$name])) {
1802 108
                    $sorted[$name] = $attributes[$name];
1803 108
                }
1804 108
            }
1805 108
            $attributes = array_merge($sorted, $attributes);
1806 108
        }
1807
1808 150
        $html = '';
1809 150
        foreach ($attributes as $name => $value) {
1810 139
            if (is_bool($value)) {
1811 17
                if ($value) {
1812 14
                    $html .= " $name";
1813 14
                }
1814 139
            } elseif (is_array($value)) {
1815 3
                if (in_array($name, static::$dataAttributes)) {
1816 2
                    foreach ($value as $n => $v) {
1817 2
                        if (is_array($v)) {
1818
                            $html .= " $name-$n='" . Json::htmlEncode($v) . "'";
1819
                        } else {
1820 2
                            $html .= " $name-$n=\"" . static::encode($v) . '"';
1821
                        }
1822 2
                    }
1823 3
                } elseif ($name === 'class') {
1824 1
                    if (empty($value)) {
1825 1
                        continue;
1826
                    }
1827 1
                    $html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
1828 2
                } elseif ($name === 'style') {
1829 1
                    if (empty($value)) {
1830 1
                        continue;
1831
                    }
1832 1
                    $html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
1833 1
                } else {
1834 1
                    $html .= " $name='" . Json::htmlEncode($value) . "'";
1835
                }
1836 139
            } elseif ($value !== null) {
1837 139
                $html .= " $name=\"" . static::encode($value) . '"';
1838 139
            }
1839 150
        }
1840
1841 150
        return $html;
1842
    }
1843
1844
    /**
1845
     * Adds a CSS class (or several classes) to the specified options.
1846
     * If the CSS class is already in the options, it will not be added again.
1847
     * If class specification at given options is an array, and some class placed there with the named (string) key,
1848
     * overriding of such key will have no effect. For example:
1849
     *
1850
     * ```php
1851
     * $options = ['class' => ['persistent' => 'initial']];
1852
     * Html::addCssClass($options, ['persistent' => 'override']);
1853
     * var_dump($options['class']); // outputs: array('persistent' => 'initial');
1854
     * ```
1855
     *
1856
     * @param array $options the options to be modified.
1857
     * @param string|array $class the CSS class(es) to be added
1858
     */
1859 5
    public static function addCssClass(&$options, $class)
1860
    {
1861 5
        if (isset($options['class'])) {
1862 4
            if (is_array($options['class'])) {
1863 2
                $options['class'] = self::mergeCssClasses($options['class'], (array) $class);
1864 2
            } else {
1865 3
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
1866 3
                $options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
1867
            }
1868 4
        } else {
1869 4
            $options['class'] = $class;
1870
        }
1871 5
    }
1872
1873
    /**
1874
     * Merges already existing CSS classes with new one.
1875
     * This method provides the priority for named existing classes over additional.
1876
     * @param array $existingClasses already existing CSS classes.
1877
     * @param array $additionalClasses CSS classes to be added.
1878
     * @return array merge result.
1879
     */
1880 4
    private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
1881
    {
1882 4
        foreach ($additionalClasses as $key => $class) {
1883 4
            if (is_int($key) && !in_array($class, $existingClasses)) {
1884 3
                $existingClasses[] = $class;
1885 4
            } elseif (!isset($existingClasses[$key])) {
1886 1
                $existingClasses[$key] = $class;
1887 1
            }
1888 4
        }
1889 4
        return array_unique($existingClasses);
1890
    }
1891
1892
    /**
1893
     * Removes a CSS class from the specified options.
1894
     * @param array $options the options to be modified.
1895
     * @param string|array $class the CSS class(es) to be removed
1896
     */
1897 1
    public static function removeCssClass(&$options, $class)
1898
    {
1899 1
        if (isset($options['class'])) {
1900 1
            if (is_array($options['class'])) {
1901 1
                $classes = array_diff($options['class'], (array) $class);
1902 1
                if (empty($classes)) {
1903 1
                    unset($options['class']);
1904 1
                } else {
1905 1
                    $options['class'] = $classes;
1906
                }
1907 1
            } else {
1908 1
                $classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
1909 1
                $classes = array_diff($classes, (array) $class);
1910 1
                if (empty($classes)) {
1911 1
                    unset($options['class']);
1912 1
                } else {
1913 1
                    $options['class'] = implode(' ', $classes);
1914
                }
1915
            }
1916 1
        }
1917 1
    }
1918
1919
    /**
1920
     * Adds the specified CSS style to the HTML options.
1921
     *
1922
     * If the options already contain a `style` element, the new style will be merged
1923
     * with the existing one. If a CSS property exists in both the new and the old styles,
1924
     * the old one may be overwritten if `$overwrite` is true.
1925
     *
1926
     * For example,
1927
     *
1928
     * ```php
1929
     * Html::addCssStyle($options, 'width: 100px; height: 200px');
1930
     * ```
1931
     *
1932
     * @param array $options the HTML options to be modified.
1933
     * @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
1934
     * array (e.g. `['width' => '100px', 'height' => '200px']`).
1935
     * @param bool $overwrite whether to overwrite existing CSS properties if the new style
1936
     * contain them too.
1937
     * @see removeCssStyle()
1938
     * @see cssStyleFromArray()
1939
     * @see cssStyleToArray()
1940
     */
1941 1
    public static function addCssStyle(&$options, $style, $overwrite = true)
1942
    {
1943 1
        if (!empty($options['style'])) {
1944 1
            $oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
1945 1
            $newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
1946 1
            if (!$overwrite) {
1947 1
                foreach ($newStyle as $property => $value) {
1948 1
                    if (isset($oldStyle[$property])) {
1949 1
                        unset($newStyle[$property]);
1950 1
                    }
1951 1
                }
1952 1
            }
1953 1
            $style = array_merge($oldStyle, $newStyle);
1954 1
        }
1955 1
        $options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
1956 1
    }
1957
1958
    /**
1959
     * Removes the specified CSS style from the HTML options.
1960
     *
1961
     * For example,
1962
     *
1963
     * ```php
1964
     * Html::removeCssStyle($options, ['width', 'height']);
1965
     * ```
1966
     *
1967
     * @param array $options the HTML options to be modified.
1968
     * @param string|array $properties the CSS properties to be removed. You may use a string
1969
     * if you are removing a single property.
1970
     * @see addCssStyle()
1971
     */
1972 1
    public static function removeCssStyle(&$options, $properties)
1973
    {
1974 1
        if (!empty($options['style'])) {
1975 1
            $style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
1976 1
            foreach ((array) $properties as $property) {
1977 1
                unset($style[$property]);
1978 1
            }
1979 1
            $options['style'] = static::cssStyleFromArray($style);
1980 1
        }
1981 1
    }
1982
1983
    /**
1984
     * Converts a CSS style array into a string representation.
1985
     *
1986
     * For example,
1987
     *
1988
     * ```php
1989
     * print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
1990
     * // will display: 'width: 100px; height: 200px;'
1991
     * ```
1992
     *
1993
     * @param array $style the CSS style array. The array keys are the CSS property names,
1994
     * and the array values are the corresponding CSS property values.
1995
     * @return string the CSS style string. If the CSS style is empty, a null will be returned.
1996
     */
1997 4
    public static function cssStyleFromArray(array $style)
1998
    {
1999 4
        $result = '';
2000 4
        foreach ($style as $name => $value) {
2001 4
            $result .= "$name: $value; ";
2002 4
        }
2003
        // return null if empty to avoid rendering the "style" attribute
2004 4
        return $result === '' ? null : rtrim($result);
2005
    }
2006
2007
    /**
2008
     * Converts a CSS style string into an array representation.
2009
     *
2010
     * The array keys are the CSS property names, and the array values
2011
     * are the corresponding CSS property values.
2012
     *
2013
     * For example,
2014
     *
2015
     * ```php
2016
     * print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
2017
     * // will display: ['width' => '100px', 'height' => '200px']
2018
     * ```
2019
     *
2020
     * @param string $style the CSS style string
2021
     * @return array the array representation of the CSS style
2022
     */
2023 3
    public static function cssStyleToArray($style)
2024
    {
2025 3
        $result = [];
2026 3
        foreach (explode(';', $style) as $property) {
2027 3
            $property = explode(':', $property);
2028 3
            if (count($property) > 1) {
2029 3
                $result[trim($property[0])] = trim($property[1]);
2030 3
            }
2031 3
        }
2032 3
        return $result;
2033
    }
2034
2035
    /**
2036
     * Returns the real attribute name from the given attribute expression.
2037
     *
2038
     * An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
2039
     * It is mainly used in tabular data input and/or input of array type. Below are some examples:
2040
     *
2041
     * - `[0]content` is used in tabular data input to represent the "content" attribute
2042
     *   for the first model in tabular input;
2043
     * - `dates[0]` represents the first array element of the "dates" attribute;
2044
     * - `[0]dates[0]` represents the first array element of the "dates" attribute
2045
     *   for the first model in tabular input.
2046
     *
2047
     * If `$attribute` has neither prefix nor suffix, it will be returned back without change.
2048
     * @param string $attribute the attribute name or expression
2049
     * @return string the attribute name without prefix and suffix.
2050
     * @throws InvalidParamException if the attribute name contains non-word characters.
2051
     */
2052 25
    public static function getAttributeName($attribute)
2053
    {
2054 25
        if (preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
2055 25
            return $matches[2];
2056
        } else {
2057
            throw new InvalidParamException('Attribute name must contain word characters only.');
2058
        }
2059
    }
2060
2061
    /**
2062
     * Returns the value of the specified attribute name or expression.
2063
     *
2064
     * For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
2065
     * See [[getAttributeName()]] for more details about attribute expression.
2066
     *
2067
     * If an attribute value is an instance of [[ActiveRecordInterface]] or an array of such instances,
2068
     * the primary value(s) of the AR instance(s) will be returned instead.
2069
     *
2070
     * @param Model $model the model object
2071
     * @param string $attribute the attribute name or expression
2072
     * @return string|array the corresponding attribute value
2073
     * @throws InvalidParamException if the attribute name contains non-word characters.
2074
     */
2075 25
    public static function getAttributeValue($model, $attribute)
2076
    {
2077 25
        if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
2078
            throw new InvalidParamException('Attribute name must contain word characters only.');
2079
        }
2080 25
        $attribute = $matches[2];
2081 25
        $value = $model->$attribute;
2082 25
        if ($matches[3] !== '') {
2083
            foreach (explode('][', trim($matches[3], '[]')) as $id) {
2084
                if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
2085
                    $value = $value[$id];
2086
                } else {
2087
                    return null;
2088
                }
2089
            }
2090
        }
2091
2092
        // https://github.com/yiisoft/yii2/issues/1457
2093 25
        if (is_array($value)) {
2094
            foreach ($value as $i => $v) {
2095
                if ($v instanceof ActiveRecordInterface) {
2096
                    $v = $v->getPrimaryKey(false);
2097
                    $value[$i] = is_array($v) ? json_encode($v) : $v;
2098
                }
2099
            }
2100 25
        } elseif ($value instanceof ActiveRecordInterface) {
2101
            $value = $value->getPrimaryKey(false);
2102
2103
            return is_array($value) ? json_encode($value) : $value;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return is_array($value) ...ncode($value) : $value; (object|integer|double|string|null|boolean) is incompatible with the return type documented by yii\helpers\BaseHtml::getAttributeValue of type string|array.

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

Let’s take a look at an example:

class Author {
    private $name;

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

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

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

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

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

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

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

Loading history...
2104
        }
2105
2106 25
        return $value;
2107
    }
2108
2109
    /**
2110
     * Generates an appropriate input name for the specified attribute name or expression.
2111
     *
2112
     * This method generates a name that can be used as the input name to collect user input
2113
     * for the specified attribute. The name is generated according to the [[Model::formName|form name]]
2114
     * of the model and the given attribute name. For example, if the form name of the `Post` model
2115
     * is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
2116
     *
2117
     * See [[getAttributeName()]] for explanation of attribute expression.
2118
     *
2119
     * @param Model $model the model object
2120
     * @param string $attribute the attribute name or expression
2121
     * @return string the generated input name
2122
     * @throws InvalidParamException if the attribute name contains non-word characters.
2123
     */
2124 36
    public static function getInputName($model, $attribute)
2125
    {
2126 36
        $formName = $model->formName();
2127 36
        if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
2128
            throw new InvalidParamException('Attribute name must contain word characters only.');
2129
        }
2130 36
        $prefix = $matches[1];
2131 36
        $attribute = $matches[2];
2132 36
        $suffix = $matches[3];
2133 36
        if ($formName === '' && $prefix === '') {
2134
            return $attribute . $suffix;
2135 36
        } elseif ($formName !== '') {
2136 36
            return $formName . $prefix . "[$attribute]" . $suffix;
2137
        } else {
2138
            throw new InvalidParamException(get_class($model) . '::formName() cannot be empty for tabular inputs.');
2139
        }
2140
    }
2141
2142
    /**
2143
     * Generates an appropriate input ID for the specified attribute name or expression.
2144
     *
2145
     * This method converts the result [[getInputName()]] into a valid input ID.
2146
     * For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
2147
     * @param Model $model the model object
2148
     * @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
2149
     * @return string the generated input ID
2150
     * @throws InvalidParamException if the attribute name contains non-word characters.
2151
     */
2152 33
    public static function getInputId($model, $attribute)
2153
    {
2154 33
        $name = strtolower(static::getInputName($model, $attribute));
2155 33
        return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
2156
    }
2157
2158
    /**
2159
     * Escapes regular expression to use in JavaScript
2160
     * @param string $regexp the regular expression to be escaped.
2161
     * @return string the escaped result.
2162
     * @since 2.0.6
2163
     */
2164
    public static function escapeJsRegularExpression($regexp)
2165
    {
2166
        $pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
2167
        $deliminator = substr($pattern, 0, 1);
2168
        $pos = strrpos($pattern, $deliminator, 1);
2169
        $flag = substr($pattern, $pos + 1);
2170
        if ($deliminator !== '/') {
2171
            $pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
2172
        } else {
2173
            $pattern = substr($pattern, 0, $pos + 1);
2174
        }
2175
        if (!empty($flag)) {
2176
            $pattern .= preg_replace('/[^igm]/', '', $flag);
2177
        }
2178
2179
        return $pattern;
2180
    }
2181
}
2182