Skip to content

Commit

Permalink
bug #969 [TwigComponent] Fix escaping stimulus attributes (1ed)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
weaverryan committed Jun 25, 2023
2 parents b06640e + 551c9d6 commit a5ba00d
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/StimulusBundle/src/Dto/StimulusAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,16 @@ public function toArray(): array
return array_merge($attributes, $this->attributes);
}

public function toEscapedArray(): array
{
$escaped = [];
foreach ($this->toArray() as $key => $value) {
$escaped[$key] = $this->escapeAsHtmlAttr($value);
}

return $escaped;
}

private function getFormattedValue(mixed $value): string
{
if ($value instanceof \Stringable || (\is_object($value) && \is_callable([$value, '__toString']))) {
Expand Down
4 changes: 4 additions & 0 deletions src/TwigComponent/src/ComponentAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ public function all(): array
*/
public function defaults(iterable $attributes): self
{
if ($attributes instanceof StimulusAttributes) {
$attributes = $attributes->toEscapedArray();
}

if ($attributes instanceof \Traversable) {
$attributes = iterator_to_array($attributes);
}
Expand Down
3 changes: 2 additions & 1 deletion src/TwigComponent/tests/Unit/ComponentAttributesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,15 @@ public function testCanAddStimulusControllerViaStimulusAttributes(): void
]);

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

$this->assertEquals([
'class' => 'foo',
'data-controller' => 'foo live',
'data-live-data-value' => '{}',
'data-foo-name-value' => 'ryan',
'data-foo-some-array-value' => '["a","b"]',
], $attributes->all());
}

Expand Down

0 comments on commit a5ba00d

Please sign in to comment.