symfony: [Serializer] MaxDepth annotation not working as expected

Symfony version(s) affected: master (pre-4.4), 4.3, probably all others

Description
The MaxDepth annotation doesn’t work as expected when multiple different classes are involved in the tree.

Current tests and examples all deal with one self-referencing class only, and pass successfully, but as soon as you hit real-world scenarios with multiple classes, they fail.

For example: I have the following class relation: tags have posts, which are owned by users. All relations are bilateral (users own posts, which have tags). I’ve annotated all such relationships with MaxDepth(1), yet when I list tags, I get a list of tags, each with a list of posts, each with its owner (with a list of their posts) and the list of its tags. The tree only seems to stop when the same class occurs MaxDepth times in the composition tree or when a circular reference is hit.

How to reproduce
I’ve extended the built-in Serializer tests slightly to demonstrate the issue, here’s the commit: symfony/serializer@ec6bfe7.

Related issues elsewhere

  • api-platform/core#1764 (see comments towards the bottom of the thread)
  • FriendsOfSymfony/FOSRestBundle#1704 (see the third comment)

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 6
  • Comments: 19 (4 by maintainers)

Most upvoted comments

Yes, please send a PR to the documentation if you have an idea how we could clarify the current behaviour.

@nrobinaubertin thanks for the link! I’ll probably end up copying your code as a solution for my case. 😃 (Edit: I switched to JMS instead, but later went back to Symfony Serializer and ended up whitelisting only specific properties at specific depths in each tree I was serializing.)

I do think it’s a bug in the feature implementation and not in the documentation though: there are separate options related to circular reference handling and it’s a bit unclear to me how this option, working the way it does, would be of added value. Plus, in that case its name would be misleading.

I just want to say that I faced the same issue. This looks like an error for sure; to be able to set how deep you want to serialize looks like a basic feature to me.

I do think this issue is still relevant and will remain such until it’s either fixed, or a new annotation is introduced to cover actual MaxDepth and not MaxDepthOfSameClass.