Skip to content

Commit a5ba00d

Browse files
committed
bug #969 [TwigComponent] Fix escaping stimulus attributes (1ed)
This PR was merged into the 2.x branch. Discussion ---------- [TwigComponent] Fix escaping stimulus attributes | Q | A | ------------- | --- | Bug fix? | yes | New feature? | no | Tickets | Fix #968 | License | MIT I think we should do this as late as possible, e.g. in `__toString` or only in twig and maybe for all the attributes. So this feels like a naive solution, but it works for now. Commits ------- 551c9d6 [TwigComponent] Fix escaping stimulus attributes
2 parents b06640e + 551c9d6 commit a5ba00d

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

src/StimulusBundle/src/Dto/StimulusAttributes.php

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,16 @@ public function toArray(): array
179179
return array_merge($attributes, $this->attributes);
180180
}
181181

182+
public function toEscapedArray(): array
183+
{
184+
$escaped = [];
185+
foreach ($this->toArray() as $key => $value) {
186+
$escaped[$key] = $this->escapeAsHtmlAttr($value);
187+
}
188+
189+
return $escaped;
190+
}
191+
182192
private function getFormattedValue(mixed $value): string
183193
{
184194
if ($value instanceof \Stringable || (\is_object($value) && \is_callable([$value, '__toString']))) {

src/TwigComponent/src/ComponentAttributes.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,10 @@ public function all(): array
6969
*/
7070
public function defaults(iterable $attributes): self
7171
{
72+
if ($attributes instanceof StimulusAttributes) {
73+
$attributes = $attributes->toEscapedArray();
74+
}
75+
7276
if ($attributes instanceof \Traversable) {
7377
$attributes = iterator_to_array($attributes);
7478
}

src/TwigComponent/tests/Unit/ComponentAttributesTest.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -134,14 +134,15 @@ public function testCanAddStimulusControllerViaStimulusAttributes(): void
134134
]);
135135

136136
$stimulusAttributes = new StimulusAttributes(new Environment(new ArrayLoader()));
137-
$stimulusAttributes->addController('foo', ['name' => 'ryan']);
137+
$stimulusAttributes->addController('foo', ['name' => 'ryan', 'some_array' => ['a', 'b']]);
138138
$attributes = $attributes->defaults($stimulusAttributes);
139139

140140
$this->assertEquals([
141141
'class' => 'foo',
142142
'data-controller' => 'foo live',
143143
'data-live-data-value' => '{}',
144144
'data-foo-name-value' => 'ryan',
145+
'data-foo-some-array-value' => '["a","b"]',
145146
], $attributes->all());
146147
}
147148

0 commit comments

Comments
 (0)