Skip to content

Commit ae725d4

Browse files
committed
add tests for hydrating/dehydrating attributes
1 parent 3123f35 commit ae725d4

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
@@ -18,7 +18,9 @@
1818
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component2;
1919
use Symfony\UX\LiveComponent\Tests\Fixture\Component\Component3;
2020
use Symfony\UX\LiveComponent\Tests\Fixture\Entity\Entity1;
21+
use Symfony\UX\TwigComponent\ComponentAttributes;
2122
use Symfony\UX\TwigComponent\ComponentFactory;
23+
use Symfony\UX\TwigComponent\HasAttributesTrait;
2224
use function Zenstruck\Foundry\create;
2325
use Zenstruck\Foundry\Test\Factories;
2426
use Zenstruck\Foundry\Test\ResetDatabase;
@@ -239,4 +241,32 @@ public function testCorrectlyUsesCustomFrontendNameInDehydrateAndHydrate(): void
239241
$this->assertSame('value1', $component->prop1);
240242
$this->assertSame('value2', $component->prop2);
241243
}
244+
245+
public function testCanDehydrateAndHydrateComponentsWithAttributes(): void
246+
{
247+
if (!class_exists(ComponentAttributes::class)) {
248+
$this->markTestSkipped('Attributes trait not available.');
249+
}
250+
251+
/** @var LiveComponentHydrator $hydrator */
252+
$hydrator = self::getContainer()->get('ux.live_component.component_hydrator');
253+
254+
$component = new class() {
255+
use HasAttributesTrait;
256+
};
257+
$instance = clone $component;
258+
$instance->attributes = new ComponentAttributes($attributes = ['class' => 'foo']);
259+
260+
$this->assertSame($attributes, $instance->attributes->all());
261+
262+
$dehydrated = $hydrator->dehydrate($instance);
263+
264+
$this->assertArrayHasKey('attributes', $dehydrated);
265+
$this->assertSame($attributes, $dehydrated['attributes']);
266+
$this->assertFalse(isset($component->prop));
267+
268+
$hydrator->hydrate($component, $dehydrated);
269+
270+
$this->assertSame($attributes, $component->attributes->all());
271+
}
242272
}

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)