1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Form\Field\Base; |
6
|
|
|
|
7
|
|
|
use Stringable; |
8
|
|
|
use Yiisoft\Html\Html; |
9
|
|
|
use Yiisoft\Html\NoEncodeStringableInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Adds functionality for processing with field content. |
13
|
|
|
*/ |
14
|
|
|
trait FieldContentTrait |
15
|
|
|
{ |
16
|
|
|
private ?bool $encodeContent = null; |
17
|
|
|
private bool $doubleEncodeContent = true; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @psalm-var array<array-key, string|Stringable> |
21
|
|
|
*/ |
22
|
|
|
private array $content = []; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @param bool|null $encode Whether to encode field content. Supported values: |
26
|
|
|
* - `null`: stringable objects that implement interface {@see NoEncodeStringableInterface} are not encoded, |
27
|
|
|
* everything else is encoded; |
28
|
|
|
* - `true`: any content is encoded; |
29
|
|
|
* - `false`: nothing is encoded. |
30
|
|
|
* Defaults to `null`. |
31
|
|
|
*/ |
32
|
3 |
|
final public function encodeContent(?bool $encode): static |
33
|
|
|
{ |
34
|
3 |
|
$new = clone $this; |
35
|
3 |
|
$new->encodeContent = $encode; |
36
|
3 |
|
return $new; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param bool $doubleEncode Whether already encoded HTML entities in field content should be encoded. |
41
|
|
|
* Defaults to `true`. |
42
|
|
|
*/ |
43
|
2 |
|
final public function doubleEncodeContent(bool $doubleEncode): static |
44
|
|
|
{ |
45
|
2 |
|
$new = clone $this; |
46
|
2 |
|
$new->doubleEncodeContent = $doubleEncode; |
47
|
2 |
|
return $new; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* @param string|Stringable ...$content Field content. |
52
|
|
|
*/ |
53
|
26 |
|
final public function content(string|Stringable ...$content): static |
54
|
|
|
{ |
55
|
26 |
|
$new = clone $this; |
56
|
26 |
|
$new->content = $content; |
57
|
26 |
|
return $new; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param string|Stringable ...$content Field content. |
62
|
|
|
*/ |
63
|
4 |
|
final public function addContent(string|Stringable ...$content): static |
64
|
|
|
{ |
65
|
4 |
|
$new = clone $this; |
66
|
4 |
|
$new->content = array_merge($new->content, array_values($content)); |
67
|
4 |
|
return $new; |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
/** |
71
|
|
|
* @return string Obtain field content considering encoding options {@see encodeContent()}. |
72
|
|
|
*/ |
73
|
79 |
|
final protected function renderContent(): string |
74
|
|
|
{ |
75
|
79 |
|
$content = ''; |
76
|
|
|
|
77
|
79 |
|
foreach ($this->content as $item) { |
78
|
25 |
|
if ($this->encodeContent || ($this->encodeContent === null && !($item instanceof NoEncodeStringableInterface))) { |
79
|
23 |
|
$item = Html::encode($item, $this->doubleEncodeContent); |
80
|
|
|
} |
81
|
|
|
|
82
|
25 |
|
$content .= $item; |
83
|
|
|
} |
84
|
|
|
|
85
|
79 |
|
return $content; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|