Open
Description
Symfony version(s) affected
6.4.x
Description
This example object with empty array properties:
class MyObject
{
#[SerializedName('entry')]
public $list = [];
#[SerializedPath("[outer][inner]")]
public $outer = [];
}
Normalized like this:
array(2) {
["entry"]=>
array(0) {
}
["outer"]=>
array(1) {
["inner"]=>
array(0) {
}
}
}
Which results in this:
<?xml version="1.0"?>
<response>
<entry/>
<outer>
<inner/>
</outer>
</response>
Depending on the XML, empty 'entry' or 'inner' might not be allowed. (maybe not even empty 'outer')
Right now, there is no easy way to make Symfony skip these empty array attributes.
I used some Custom Normalizer, but that might not be the best idea
How to reproduce
Example code from my php Sandbox: https://phpsandbox.io/e/x/uqryl
class MyObject
{
#[SerializedName('entry')]
public $list = [];
#[SerializedPath("[outer][inner]")]
public $outer = [];
}
$loaderChain = new LoaderChain([
new AttributeLoader(),
]);
$classMetadataFactory = new ClassMetadataFactory($loaderChain);
$nameConverter = new MetadataAwareNameConverter($classMetadataFactory);
$phpDocExtractor = new PhpDocExtractor();
$reflectionExtractor = new ReflectionExtractor();
$typeExtractor = new PropertyInfoExtractor(
typeExtractors: [ new ConstructorExtractor([$phpDocExtractor]), $phpDocExtractor, $reflectionExtractor]
);
$serializer = new Serializer(
normalizers: [
new ArrayDenormalizer(),
new ObjectNormalizer($classMetadataFactory, $nameConverter, null, $typeExtractor),
],
encoders: ['xml' => new XmlEncoder()]
);
$object = new MyObject();
try {
var_dump(
$serializer->normalize($object, 'xml')
);
var_dump($serializer->serialize($object, 'xml', [
XmlEncoder::FORMAT_OUTPUT => true
]));
} catch (Throwable $t) {
var_dump($t);
}
Possible Solution
Because the problem is most likely for XML format, it might need to only affect XML when normalizing
Additional Context
No response