Skip to content

Commit 03c655a

Browse files
committed
add tests for hydrating/dehydrating attributes
1 parent 8035b07 commit 03c655a

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

src/LiveComponent/tests/Integration/LiveComponentHydratorTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@
1919
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component2;
2020
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component3;
2121
use Symfony\UX\LiveComponent\Tests\Fixture\Entity\Entity1;
22+
use Symfony\UX\TwigComponent\ComponentAttributes;
2223
use Symfony\UX\TwigComponent\ComponentFactory;
24+
use Symfony\UX\TwigComponent\HasAttributesTrait;
2325
use function Zenstruck\Foundry\create;
2426
use Zenstruck\Foundry\Test\Factories;
2527
use Zenstruck\Foundry\Test\ResetDatabase;
@@ -265,4 +267,32 @@ public function testCanDehydrateAndHydrateArrays(): void
265267

266268
$this->assertSame($instance->prop, $component->prop);
267269
}
270+
271+
public function testCanDehydrateAndHydrateComponentsWithAttributes(): void
272+
{
273+
if (!class_exists(ComponentAttributes::class)) {
274+
$this->markTestSkipped('Attributes trait not available.');
275+
}
276+
277+
/** @var LiveComponentHydrator $hydrator */
278+
$hydrator = self::getContainer()->get('ux.live_component.component_hydrator');
279+
280+
$component = new class() {
281+
use HasAttributesTrait;
282+
};
283+
$instance = clone $component;
284+
$instance->attributes = new ComponentAttributes($attributes = ['class' => 'foo']);
285+
286+
$this->assertSame($attributes, $instance->attributes->all());
287+
288+
$dehydrated = $hydrator->dehydrate($instance);
289+
290+
$this->assertArrayHasKey('attributes', $dehydrated);
291+
$this->assertSame($attributes, $dehydrated['attributes']);
292+
$this->assertFalse(isset($component->prop));
293+
294+
$hydrator->hydrate($component, $dehydrated);
295+
296+
$this->assertSame($attributes, $component->attributes->all());
297+
}
268298
}

src/TwigComponent/src/HasAttributesTrait.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ trait HasAttributesTrait
2424
#[LiveProp(hydrateWith: 'hydrateAttributes', dehydrateWith: 'dehydrateAttributes')]
2525
public ComponentAttributes $attributes;
2626

27-
public function setAttributes(array $attributes): void
27+
public function setAttributes(array|ComponentAttributes $attributes): void
2828
{
29-
$this->attributes = new ComponentAttributes($attributes);
29+
$this->attributes = is_array($attributes) ? new ComponentAttributes($attributes) : $attributes;
3030
}
3131

3232
#[PostMount(priority: -1000)]

0 commit comments

Comments
 (0)