Skip to content

[LiveComponent] Fix BC break when using PropertyTypeExtractorInterface::getType() on a #[LiveProp] property x when getter getX exists #2922

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

Open
wants to merge 2 commits into
base: 2.x
Choose a base branch
from
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,7 @@ function (ChildDefinition $definition, AsLiveComponent $attribute) {
->setArguments([
new Reference('ux.twig_component.component_factory'),
new Reference('property_info'),
new Reference('type_info.resolver', ContainerInterface::NULL_ON_INVALID_REFERENCE),
])
->addTag('kernel.reset', ['method' => 'reset'])
;
Expand Down
40 changes: 25 additions & 15 deletions src/LiveComponent/src/Metadata/LiveComponentMetadataFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@

use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
use Symfony\Component\PropertyInfo\Type as LegacyType;
use Symfony\Component\TypeInfo\Type\IntersectionType;
use Symfony\Component\TypeInfo\Type\NullableType;
use Symfony\Component\TypeInfo\Type\UnionType;
use Symfony\Component\TypeInfo\Type;
use Symfony\Component\TypeInfo\Type\CollectionType;
use Symfony\Component\TypeInfo\TypeResolver\TypeResolver;
use Symfony\Contracts\Service\ResetInterface;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\TwigComponent\ComponentFactory;
Expand All @@ -33,7 +33,11 @@ class LiveComponentMetadataFactory implements ResetInterface
public function __construct(
private ComponentFactory $componentFactory,
private PropertyTypeExtractorInterface $propertyTypeExtractor,
private ?TypeResolver $typeResolver = null,
) {
if (method_exists($this->propertyTypeExtractor, 'getType') && !$this->typeResolver) {
throw new \LogicException('Symfony TypeInfo is required to use LiveProps. Try running "composer require symfony/type-info".');
}
Comment on lines +38 to +40
Copy link
Member Author

@Kocal Kocal Jul 14, 2025

Choose a reason for hiding this comment

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

Should not happens since PropertyTypeInfoExtractor::getType() exists since 7.1, which also ship TypeInfo, but just in case..

}

public function getMetadata(string $name): LiveComponentMetadata
Expand Down Expand Up @@ -77,13 +81,13 @@ public function createPropMetadatas(\ReflectionClass $class): array

public function createLivePropMetadata(string $className, string $propertyName, \ReflectionProperty $property, LiveProp $liveProp): LivePropMetadata|LegacyLivePropMetadata
{
$reflectionType = $property->getType();
if ($reflectionType instanceof \ReflectionUnionType || $reflectionType instanceof \ReflectionIntersectionType) {
throw new \LogicException(\sprintf('Union or intersection types are not supported for LiveProps. You may want to change the type of property %s in %s.', $property->getName(), $property->getDeclaringClass()->getName()));
}

// BC layer when "symfony/type-info" is not available
if (!method_exists($this->propertyTypeExtractor, 'getType')) {
$type = $property->getType();
if ($type instanceof \ReflectionUnionType || $type instanceof \ReflectionIntersectionType) {
throw new \LogicException(\sprintf('Union or intersection types are not supported for LiveProps. You may want to change the type of property %s in %s.', $property->getName(), $property->getDeclaringClass()->getName()));
}

$infoTypes = $this->propertyTypeExtractor->getTypes($className, $propertyName) ?? [];

$collectionValueType = null;
Expand All @@ -96,14 +100,14 @@ public function createLivePropMetadata(string $className, string $propertyName,
}
}

if (null === $type && null === $collectionValueType && isset($infoTypes[0])) {
if (null === $reflectionType && null === $collectionValueType && isset($infoTypes[0])) {
$infoType = LegacyType::BUILTIN_TYPE_OBJECT === $infoTypes[0]->getBuiltinType() ? $infoTypes[0]->getClassName() : $infoTypes[0]->getBuiltinType();
$isTypeBuiltIn = null === $infoTypes[0]->getClassName();
$isTypeNullable = $infoTypes[0]->isNullable();
} else {
$infoType = $type?->getName();
$isTypeBuiltIn = $type?->isBuiltin() ?? false;
$isTypeNullable = $type?->allowsNull() ?? true;
$infoType = $reflectionType?->getName();
$isTypeBuiltIn = $reflectionType?->isBuiltin() ?? false;
$isTypeNullable = $reflectionType?->allowsNull() ?? true;
}

return new LegacyLivePropMetadata(
Expand All @@ -115,10 +119,16 @@ public function createLivePropMetadata(string $className, string $propertyName,
$collectionValueType
);
} else {
$type = $this->propertyTypeExtractor->getType($className, $property->getName());
$infoType = $this->propertyTypeExtractor->getType($className, $property->getName());

$collectionValueType = $infoType instanceof CollectionType ? $infoType->getCollectionValueType() : null;

if ($type instanceof UnionType && !$type instanceof NullableType || $type instanceof IntersectionType) {
throw new \LogicException(\sprintf('Union or intersection types are not supported for LiveProps. You may want to change the type of property "%s" in "%s".', $propertyName, $className));
if (null !== $collectionValueType && null !== $infoType) {
Copy link
Contributor

Choose a reason for hiding this comment

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

Suggested change
if (null !== $collectionValueType && null !== $infoType) {
if ($infoType instance of CollectionType) {

Seems to be enough no?

Copy link
Member Author

Choose a reason for hiding this comment

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

I think yes, it would ease the readability too

$type = $infoType;
} elseif (null !== $reflectionType) {
$type = $this->typeResolver->resolve($reflectionType);
} else {
$type = Type::mixed();
}

return new LivePropMetadata($property->getName(), $liveProp, $type);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\LiveComponent\Tests\Fixtures\Component;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\UX\LiveComponent\Attribute\AsLiveComponent;
use Symfony\UX\LiveComponent\Attribute\LiveProp;
use Symfony\UX\LiveComponent\ComponentWithFormTrait;
use Symfony\UX\LiveComponent\DefaultActionTrait;
use Symfony\UX\LiveComponent\Tests\Fixtures\Entity\User;
use Symfony\UX\LiveComponent\Tests\Fixtures\Form\UserFormType;

#[AsLiveComponent('form_with_user_interface', template: 'components/form_with_user_interface.html.twig')]
class FormWithUserInterfaceComponent extends AbstractController
{
use ComponentWithFormTrait;
use DefaultActionTrait;

#[LiveProp]
public User $user;

protected function instantiateForm(): FormInterface
{
return $this->createForm(UserFormType::class, $this->user);
}
}
57 changes: 57 additions & 0 deletions src/LiveComponent/tests/Fixtures/Entity/User.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\LiveComponent\Tests\Fixtures\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;

#[ORM\Entity]
class User implements UserInterface
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column(type: 'integer')]
public $id;

#[ORM\Column(type: 'string', length: 180, unique: true)]
public $username;

public function getRoles(): array
{
return ['ROLE_USER'];
}

public function eraseCredentials(): void
{
// no-op
}

public function getUsername(): string
{
return $this->getUserIdentifier();
}

public function getUserIdentifier(): string
{
return $this->username;
}

public function getPassword(): ?string
{
return null;
}

public function getSalt(): ?string
{
return null;
}
}
35 changes: 35 additions & 0 deletions src/LiveComponent/tests/Fixtures/Form/UserFormType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\UX\LiveComponent\Tests\Fixtures\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\UX\LiveComponent\Tests\Fixtures\Entity\User;

class UserFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', TextType::class)
;
}

public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<div{{ attributes }}>
{{ form(form) }}
</div>
38 changes: 38 additions & 0 deletions src/LiveComponent/tests/Functional/Form/ComponentWithFormTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,17 @@
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\Form\FormFactoryInterface;
use Symfony\UX\LiveComponent\Tests\Fixtures\Component\FormWithCollectionTypeComponent;
use Symfony\UX\LiveComponent\Tests\Fixtures\Entity\User;
use Symfony\UX\LiveComponent\Tests\Fixtures\Factory\CategoryFixtureEntityFactory;
use Symfony\UX\LiveComponent\Tests\Fixtures\Form\BlogPostFormType;
use Symfony\UX\LiveComponent\Tests\LiveComponentTestHelper;
use Zenstruck\Browser\Test\HasBrowser;
use Zenstruck\Foundry\Test\Factories;
use Zenstruck\Foundry\Test\ResetDatabase;

use function Zenstruck\Foundry\Persistence\persist;
use function Zenstruck\Foundry\Persistence\refresh;

/**
* @author Jakub Caban <[email protected]>
*/
Expand Down Expand Up @@ -450,4 +454,38 @@ public function testDataModelAttributeAutomaticallyAdded(): void
->assertElementAttributeContains('form', 'data-model', 'on(change)|*')
;
}

public function testFormWithLivePropContainingAnEntityImplementingAnInterface(): void
{
$user = persist(User::class, ['username' => 'Fabien']);
self::assertInstanceOf(User::class, $user);
self::assertEquals(1, $user->id);
self::assertEquals('Fabien', $user->username);

$mounted = $this->mountComponent('form_with_user_interface', [
'user' => $user,
]);

$dehydrated = $this->dehydrateComponent($mounted)->getProps();

$this->browser()
->post('/_components/form_with_user_interface', [
'body' => [
'data' => json_encode([
'props' => $dehydrated,
'updated' => [
'user_form.username' => 'Nicolas',
'validatedFields' => ['user_form.username'],
],
]),
],
])
->assertStatus(200)
->assertElementAttributeContains('form', 'data-model', 'on(change)|*')
;

refresh($user);
self::assertEquals(1, $user->id);
self::assertEquals('Nicolas', $user->username);
}
}
22 changes: 22 additions & 0 deletions src/LiveComponent/tests/Integration/LiveComponentHydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
use Symfony\UX\LiveComponent\Tests\Fixtures\Entity\Entity1;
use Symfony\UX\LiveComponent\Tests\Fixtures\Entity\Entity2;
use Symfony\UX\LiveComponent\Tests\Fixtures\Entity\ProductFixtureEntity;
use Symfony\UX\LiveComponent\Tests\Fixtures\Entity\User;
use Symfony\UX\LiveComponent\Tests\Fixtures\Enum\EmptyStringEnum;
use Symfony\UX\LiveComponent\Tests\Fixtures\Enum\IntEnum;
use Symfony\UX\LiveComponent\Tests\Fixtures\Enum\StringEnum;
Expand Down Expand Up @@ -336,6 +337,27 @@ public function onEntireEntityUpdated($oldValue)
;
}];

yield 'Persisted entity: (de)hydration works correctly to/from id, when the entity implements an interface' => [function () {
$user = persist(User::class, [
'username' => 'Fabien',
]);
\assert($user instanceof User);

return HydrationTest::create(new class {
#[LiveProp]
public User $user;
})
->mountWith(['user' => $user])
->assertDehydratesTo(['user' => $user->id])
->assertObjectAfterHydration(function (object $object) use ($user) {
self::assertSame(
$user->id,
$object->user->id
);
})
;
}];

yield 'Persisted entity: writable CAN be changed via id' => [function () {
$entityOriginal = persist(Entity1::class);
$entityNext = persist(Entity1::class);
Expand Down
Loading