Skip to content

Commit 8d5d1a3

Browse files
committed
Fixin bug with using attributes.add() on a non-live component
1 parent acb7676 commit 8d5d1a3

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

src/TwigComponent/src/ComponentAttributes.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,10 +108,10 @@ public function add(AbstractStimulusDto $stimulusDto): self
108108
$controllersAttributes = $stimulusDto->toArray();
109109
$attributes = $this->attributes;
110110

111-
$attributes['data-controller'] = implode(' ', array_merge(
112-
explode(' ', $attributes['data-controller']),
111+
$attributes['data-controller'] = trim(implode(' ', array_merge(
112+
explode(' ', $attributes['data-controller'] ?? ''),
113113
explode(' ', $controllersAttributes['data-controller'] ?? [])
114-
));
114+
)));
115115
unset($controllersAttributes['data-controller']);
116116

117117
$clone = new self($attributes);

src/TwigComponent/tests/Unit/ComponentAttributesTest.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,29 @@ public function testCanAddStimulusController(): void
8888
], $attributes->all());
8989
}
9090

91+
public function testCanAddStimulusControllerIfNoneAlreadyPresent(): void
92+
{
93+
$attributes = new ComponentAttributes([
94+
'class' => 'foo',
95+
]);
96+
97+
$controllerDto = $this->createMock(AbstractStimulusDto::class);
98+
$controllerDto->expects(self::once())
99+
->method('toArray')
100+
->willReturn([
101+
'data-controller' => 'foo bar',
102+
'data-foo-name-value' => 'ryan',
103+
]);
104+
105+
$attributes = $attributes->add($controllerDto);
106+
107+
$this->assertEquals([
108+
'class' => 'foo',
109+
'data-controller' => 'foo bar',
110+
'data-foo-name-value' => 'ryan',
111+
], $attributes->all());
112+
}
113+
91114
public function testBooleanBehaviour(): void
92115
{
93116
$attributes = new ComponentAttributes(['disabled' => true]);

0 commit comments

Comments
 (0)