Dennis de Best
Dennis de Best

Reputation: 1108

symfony 4.2 max_depth_handler serializer how to implement?

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

Upvotes: 3

Views: 4942

Answers (1)

fgamess
fgamess

Reputation: 1324

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

Upvotes: 1

Related Questions