Skip to content

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

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
Hanmac opened this issue Nov 5, 2024 · 3 comments

Comments

@Hanmac
Copy link
Contributor

Hanmac commented Nov 5, 2024

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

@Bryce-Colton
Copy link

I've been here.

Simple solution : use null value instead empty array and use in context AbstractObjectNormalizer::SKIP_NULL_VALUES => true,

It was more relaxing to allow null for every DTO fields and to validate data with validation constraints.

@Hanmac
Copy link
Contributor Author

Hanmac commented Jan 28, 2025

@Bryce-Colton maybe, i prefer to have the properties be typed as array, and init as []

Because having them typed as ?array just so i can return null kinda makes it more complicated.
Also now i need to handle empty array vs null array

for this, i added this Normalizer that does the work for me:

class EmptyArrayNormalizer implements NormalizerInterface
{

    /**
     * @inheritDoc
     */
    public function normalize(mixed $object, ?string $format = null, array $context = []): array|null
    {
        return null;
    }

    /**
     * @inheritDoc
     */
    public function supportsNormalization(mixed $data, ?string $format = null): bool
    {
        return is_array($data) && empty($data);
    }

    public function getSupportedTypes(?string $format): array
    {
        return ['object' => null, '*' => false];
    }
}

@Bryce-Colton
Copy link

Nice, your solution is totally fine regarding your needs.

So, I think this is not a bug from the serializer.

Finally you've asked for an enhancement, in XML context, to have a possibility to skip empty array.

You should propose a PR :)

I think your normalizer is correct if you add a mean to enable it by the serializer context

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants