Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

[Serializer][XmlEncoder] Serialize/Normalize Collections properties result in faulty XML, should be skipped entirely #58768

Copy link
Copy link
Open
@Hanmac

Description

@Hanmac
Issue body actions

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.