Skip to content

Commit e4ab138

Browse files
committed
feature #319 [TwigComponent] Allow to pass stringable object as non mapped component attribute (norkunas)
This PR was merged into the 2.x branch. Discussion ---------- [TwigComponent] Allow to pass stringable object as non mapped component attribute | Q | A | ------------- | --- | Bug fix? | no | New feature? | yes | Tickets | N/A | License | MIT Sometimes we have some value objects that are meant to be provided as stimulus controller values and when using `{{ component('..', { 'data-item-id-param': objectUuid }) }}` it throws an exception that attribute must be scalar. Now it will allow to accept these objects. cc `@kbond` Commits ------- c1194db [TwigComponent] Allow to pass stringable object as non mapped component attribute
2 parents 5eed770 + c1194db commit e4ab138

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

src/TwigComponent/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
# CHANGELOG
22

3+
## 2.2
4+
5+
- Allow to pass stringable object as non mapped component attribute
6+
37
## 2.1
48

59
- Make public component properties available directly in the template (`{{ prop }}` vs `{{ this.prop }}`).

src/TwigComponent/src/ComponentFactory.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,10 @@ public function create(string $name, array $data = []): MountedComponent
7171

7272
// ensure remaining data is scalar
7373
foreach ($data as $key => $value) {
74+
if ($value instanceof \Stringable) {
75+
continue;
76+
}
77+
7478
if (!\is_scalar($value) && null !== $value) {
7579
throw new \LogicException(sprintf('Unable to use "%s" (%s) as an attribute. Attributes must be scalar or null. If you meant to mount this value on "%s", make sure "$%1$s" is a writable property or create a mount() method with a "$%1$s" argument.', $key, get_debug_type($value), $component::class));
7680
}

src/TwigComponent/tests/Integration/ComponentFactoryTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,18 @@ public function testExceptionThrownIfUnableToWritePassedDataToPropertyAndIsNotSc
9898
$this->createComponent('component_a', ['propB' => 'B', 'service' => new \stdClass()]);
9999
}
100100

101+
public function testStringableObjectCanBePassedToComponent(): void
102+
{
103+
$attributes = (string) $this->factory()->create('component_a', ['propB' => 'B', 'data-item-id-param' => new class() {
104+
public function __toString(): string
105+
{
106+
return 'test';
107+
}
108+
}])->getAttributes();
109+
110+
self::assertSame(' data-item-id-param="test"', $attributes);
111+
}
112+
101113
public function testTwigComponentServiceTagMustHaveKey(): void
102114
{
103115
$this->expectException(LogicException::class);

0 commit comments

Comments
 (0)