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 ( cd2d3a...6886d6 )
by Robert
09:38
created

BaseHtml::ol()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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