Closed
Description
Symfony version(s) affected
7.0.4 & 6.4.4
Description
When serializing a doctrine proxy of an entity and using the ignored attribute on a property of the entity, I get the error :
User Notice: Undefined property: Proxies_CG_\App\Entity\ChildEntity::$lazyObjectState
in /home/../vendor/symfony/property-access/PropertyAccessor.php on line 408
Removing the property with the #[Ignore] attribute fixes the problem.
How to reproduce
https://github.com/alexandre-le-borgne/bug-symfony-phpdoc-serialization
Diff: alexandre-le-borgne/bug-symfony-phpdoc-serialization@07b80b9
// IndexController.php
#[AsController]
class IndexController {
public function __construct(private SerializerInterface $serializer, private EntityManagerInterface $doctrine)
{
}
#[Route('/')]
public function __invoke()
$parent = $this->doctrine->find(ParentEntity::class, 1);
$model = new ExampleModel();
// Trying to serialize an object containing a proxy from doctrine
$model->childEntity = $parent->getChildEntity();
dd($this->serializer->normalize($model));
}
}
#[Entity]
class ParentEntity
{
#[Id]
#[Column]
#[GeneratedValue]
private int $id;
#[OneToOne(cascade: ['persist'])]
private ChildEntity $childEntity;
public function getId(): int
{
return $this->id;
}
public function getChildEntity(): ChildEntity
{
return $this->childEntity;
}
public function setChildEntity(ChildEntity $childEntity): void
{
$this->childEntity = $childEntity;
}
}
#[Entity]
class ChildEntity
{
#[Id]
#[Column]
#[GeneratedValue]
private int $id;
#[Ignore]
public string $ignored = 'ignored';
public function getId(): int
{
return $this->id;
}
}
class ExampleModel
{
/**
* @var ChildEntity
*/
public ChildEntity $childEntity;
}
class ChildEntity
{
#[Id]
#[Column]
#[GeneratedValue]
private int $id;
#[Ignore]
public string $ignored = 'ignored';
public function getId(): int
{
return $this->id;
}
}
Removing the property "$ignored" with the Ignore attribute in the ChildEntity fixes the problem.
Possible Solution
Add in config/framework.yaml
framework:
serializer:
default_context:
ignored_attributes:
- '__initializer__'
- '__cloner__'
- '__isInitialized__'
- 'lazyObjectState'
- 'lazyObjectInitialized'
- 'lazyObjectAsInitialized'
Additional Context
Seems related to the code in AbstractNormalizer.php
$ignoreUsed = false;
// ...
if (!$ignoreUsed && [] === $groups && $allowExtraAttributes) {
// Backward Compatibility with the code using this method written before the introduction of @Ignore
return false;
}
return $allowedAttributes;