Description
Symfony version(s) affected: 5.2.4
Description
When using simple normalization - the fix introduced with this pull request: #38900 is working correctly. This is because the property metadata is read with reflection during the process and if the property is not initialized the above PR does not include it.
But when we're using groups to perform normalization, then we have to supply a class metadata factory that reads those. After using the factory, however, the typed properties are not checked whether they are initialized or not and are directly included.
This results in the same error that the above PR is trying to fix, namely:
PHP Fatal error: Uncaught Error: Typed property DataClass::$unInitialized must not be accessed before initialization in /path/to/vendor/symfony/property-access/PropertyAccessor.php:438
How to reproduce
class DataClass
{
#[Groups(['foo'])]
public string $unInitialized;
#[Groups(['foo'])]
public string $initialized = 'value';
#[Groups(['bar'])]
public string $initialized2 = 'value';
}
$object = new DataClass();
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer($classMetadataFactory);
$normalizer->normalize($object, context: ['groups' => 'foo']);
Possible Solution
May be include whether the property is initialized in the metadata? But that would result in an issue when it's cached.
May be when the property accessor tries to read it and it founds that it's not initialized it can be silently excluded from the result?
Additional context
I'm using PHP8, found that bug when I was using API Platform, but it ultimately goes down to how the normalizer work in Symfony.