Skip to content

[Twig] Allow string[] for ComponentAttribute values #1415

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/TwigComponent/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
# CHANGELOG

## Unreleased

- Allow `string[]` for component attribute values (filter non-strings).

## 2.13.0

- [BC BREAK] Add component metadata to `PreMountEvent` and `PostMountEvent`
Expand Down
39 changes: 33 additions & 6 deletions src/TwigComponent/src/ComponentAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,24 +21,24 @@
*/
final class ComponentAttributes
{
private bool $normalized = false;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This normalization tracking is required because of how #1041 was implemented. (it first sets all passed values as attributes, then removes the ones that are defined)


/**
* @param array<string, string|bool> $attributes
* @param array<string, string|bool|string[]> $attributes
*/
public function __construct(private array $attributes)
{
}

public function __toString(): string
{
$this->ensureNormalized();

return array_reduce(
array_keys($this->attributes),
function (string $carry, string $key) {
$value = $this->attributes[$key];

if (!\is_scalar($value) && null !== $value) {
throw new \LogicException(sprintf('A "%s" prop was passed when creating the component. No matching "%s" property or mount() argument was found, so we attempted to use this as an HTML attribute. But, the value is not a scalar (it\'s a %s). Did you mean to pass this to your component or is there a typo on its name?', $key, $key, get_debug_type($value)));
}

if (null === $value) {
trigger_deprecation('symfony/ux-twig-component', '2.8.0', 'Passing "null" as an attribute value is deprecated and will throw an exception in 3.0.');
$value = true;
Expand All @@ -59,7 +59,7 @@ function (string $carry, string $key) {
*/
public function all(): array
{
return $this->attributes;
return $this->ensureNormalized()->attributes;
}

/**
Expand All @@ -79,6 +79,8 @@ public function defaults(iterable $attributes): self
$attributes = iterator_to_array($attributes);
}

self::normalize($attributes);

foreach ($this->attributes as $key => $value) {
if (\in_array($key, ['class', 'data-controller', 'data-action'], true) && isset($attributes[$key])) {
$attributes[$key] = "{$attributes[$key]} {$value}";
Expand Down Expand Up @@ -157,4 +159,29 @@ public function remove($key): self

return new self($attributes);
}

private function ensureNormalized(): self
{
if ($this->normalized) {
return $this;
}

self::normalize($this->attributes);
$this->normalized = true;

return $this;
}

private static function normalize(array &$attributes): void
{
foreach ($attributes as $key => &$value) {
if (\is_array($value) && array_is_list($value)) {
$value = implode(' ', array_filter($value, static fn ($v) => \is_string($v) && '' !== $v));
}

if (!\is_scalar($value) && null !== $value) {
throw new \LogicException(sprintf('A "%s" prop was passed when creating the component. No matching "%s" property or mount() argument was found, so we attempted to use this as an HTML attribute. But, the value is not a scalar (it\'s a %s). Did you mean to pass this to your component or is there a typo on its name?', $key, $key, get_debug_type($value)));
}
}
}
}
26 changes: 26 additions & 0 deletions src/TwigComponent/tests/Unit/ComponentAttributesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,30 @@ public function testNullBehaviour(): void
$this->assertSame(['disabled' => null], $attributes->all());
$this->assertSame(' disabled', (string) $attributes);
}

public function testCannotPassNonScalarValues(): void
{
$this->expectException(\LogicException::class);

(string) new ComponentAttributes(['data-foo' => new \stdClass()]);
}

public function testListAttributeValues(): void
{
$attributes = new ComponentAttributes([
'style' => ['foo', null, false, true, '', new \stdClass(), 'bar'],
'class' => ['baz', ''],
]);

$this->assertSame(' style="foo bar" class="baz"', (string) $attributes);
$this->assertSame(['style' => 'foo bar', 'class' => 'baz'], $attributes->all());

$attributes = $attributes->defaults([
'style' => ['baz', false],
'class' => ['', 'qux'],
]);

$this->assertSame(' style="foo bar" class="qux baz"', (string) $attributes);
$this->assertSame(['style' => 'foo bar', 'class' => 'qux baz'], $attributes->all());
}
}