GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 97c43c...6b8cf1 )
by Robert
18:45
created

BaseHtml::removeCssClass()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 21
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 5

Importance

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