3

Hey just an hour ago I asked a question about the new circular_reference_handler in symfony 4.2's serializer.

(use the "circular_reference_handler" key of the context instead symfony 4.2)

The answer to that question leads me to a new problem of the maximum nesting level reached.

In the documentation (https://symfony.com/doc/current/components/serializer.html#handling-serialization-depth)

There is no mention of this context key or how to implement it.

If I use the example of the circular_reference_handler of my previous question i'll add the context key in the framework.yaml file under :

framework:
  serializer:
    max_depth_handler: 'App\Serializer\MyMaxDepthHandler'

And create the class

namespace App\Serializer;


class MyMaxDepthHandler
    {
    public function __invoke($object){
        //TODO how to handle this
    }
}

And in order for the serializer to use this handler I set the context for the serialize function :

$this->serializer->serialize($object, 'json', ['enable_max_depth' => true]);

Now my question is how do I handle this ? Does anyone have an example of what to put in the body of this __invoke function ?

Any help would be greatly appreciated

Dennis de Best
  • 1,078
  • 13
  • 30
  • turns out the __invoke function can take more arguments ($innerObject, $outerObject, $attributeName), I still do not know what to do with these in the function body however – Dennis de Best Feb 12 '19 at 09:57
  • Hi, can I know if you've solved this problem? I also met the same problem. – yifei3212 May 22 '19 at 05:55

1 Answers1

1

So I would simply do this:

<?php

use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

$this->serializer->serialize($object, 'json', [ObjectNormalizer::ENABLE_MAX_DEPTH => true, ObjectNormalizer::MAX_DEPTH_HANDLER => new MyMaxDepthHandler()]);

About the code inside __invoke, you can return whatever data you need in fact. For example just return the id of the related object. Useful in some case for the output json And you need to update your __invoke method like this:

<?php

namespace App\Serializer;

class MyMaxDepthHandler
{
    public function __invoke($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []){
        return $innerObject->id;
    }
}

You can find a detailled explanation in the Handling Serialization Depth section of the documentation

I guess the Serializer ends by calling normalize inside when you call the serialize method but double check about it. If it is not the case maybe call the normalize method directly in case this solution does not work. Because the documentation provide an example only with normalize

fgamess
  • 1,276
  • 2
  • 13
  • 25