Skip to content

Commit

Permalink
minor #9427 [Serializer] Max depth handler support (dunglas)
Browse files Browse the repository at this point in the history
This PR was merged into the master branch.

Discussion
----------

[Serializer] Max depth handler support

Documents symfony/symfony#26108. Closes #9317 and #9229.

Commits
-------

ef46c8c [Serializer] Max depth handler support
  • Loading branch information
javiereguiluz committed Mar 12, 2018
2 parents fd879cc + ef46c8c commit 4bb4abf
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions components/serializer.rst
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,54 @@ because it is deeper than the configured maximum depth of 2::
);
*/

Instead of throwing an exception, a custom callable can be executed when the maximum depth is reached. This is especially
useful when serializing entities having unique identifiers::

use Doctrine\Common\Annotations\AnnotationReader;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Annotation\MaxDepth;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class Foo
{
public $id;
/**
* @MaxDepth(1)
*/
public $child;
}

$level1 = new Foo();
$level1->id = 1;

$level2 = new Foo();
$level2->id = 2;
$level1->child = $level2;

$level3 = new Foo();
$level3->id = 3;
$level2->child = $level3;

$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$normalizer = new ObjectNormalizer($classMetadataFactory);
$normalizer->setMaxDepthHandler(function ($foo) {
return '/foos/'.$foo->id;
});

$serializer = new Serializer(array($normalizer));

$result = $serializer->normalize($level1, null, array(ObjectNormalizer::ENABLE_MAX_DEPTH => true));
/*
$result = array(
'id' => 1,
'child' => array(
'id' => 2,
'child' => '/foos/3',
);
*/

Handling Arrays
---------------

Expand Down

0 comments on commit 4bb4abf

Please sign in to comment.