@@ -630,6 +630,101 @@ having unique identifiers::
630630 var_dump($serializer->serialize($org, 'json'));
631631 // {"name":"Les-Tilleuls.coop","members":[{"name":"K\u00e9vin", organization: "Les-Tilleuls.coop"}]}
632632
633+ Handling Serialization Depth
634+ ----------------------------
635+
636+ The Serializer component is able to detect and limit the serialization depth.
637+ It is especially useful when serializing large trees. Assume the following data
638+ structure::
639+
640+ namespace Acme;
641+
642+ class MyObj
643+ {
644+ public $foo;
645+
646+ /**
647+ * @var self
648+ */
649+ public $child;
650+ }
651+
652+ $level1 = new MyObj();
653+ $level1->foo = 'level1';
654+
655+ $level2 = new MyObj();
656+ $level2->foo = 'level2';
657+ $level1->child = $level2;
658+
659+ $level3 = new MyObj();
660+ $level3->foo = 'level3';
661+ $level2->child = $level3;
662+
663+ The serializer can be configured to set a maximum depth for a given property.
664+ Here, we set it to 2 for the ``$child `` property:
665+
666+ .. configuration-block ::
667+
668+ .. code-block :: php-annotations
669+
670+ use Symfony\Component\Serializer\Annotation\MaxDepth;
671+
672+ namespace Acme;
673+
674+ class MyObj
675+ {
676+ /**
677+ * @MaxDepth(2)
678+ */
679+ public $foo;
680+
681+ // ...
682+ }
683+
684+ .. code-block :: yaml
685+
686+ Acme\MyObj :
687+ attributes :
688+ foo :
689+ max_depth : 2
690+
691+ .. code-block :: xml
692+
693+ <?xml version =" 1.0" ?>
694+ <serializer xmlns =" http://symfony.com/schema/dic/serializer-mapping"
695+ xmlns : xsi =" http://www.w3.org/2001/XMLSchema-instance"
696+ xsi : schemaLocation =" http://symfony.com/schema/dic/serializer-mapping
697+ http://symfony.com/schema/dic/serializer-mapping/serializer-mapping-1.0.xsd"
698+ >
699+ <class name =" Acme\MyObj" >
700+ <attribute name =" foo" >
701+ <max-depth >2</max-depth >
702+ </attribute >
703+ </serializer >
704+
705+ The metadata loader corresponding to the chosen format must be configured in
706+ order to use this feature. It is done automatically when using the Symfony
707+ Standard Edition. When using the standalone component, refer to
708+ :ref: `the groups documentation <component-serializer-attributes-groups >` to
709+ learn how to do that.
710+
711+ The check is only done if the ``enable_max_depth `` key of the serializer context
712+ is set to ``true ``. In the following example, the third level is not serialized
713+ because it is deeper than the configured maximum depth of 2::
714+
715+ $result = $serializer->normalize($level1, null, array('enable_max_depth' => true));
716+ /*
717+ $result = array(
718+ 'foo' => 'level1',
719+ 'child' => array(
720+ 'foo' => 'level2',
721+ 'child' => array(
722+ 'child' => null,
723+ ),
724+ ),
725+ );
726+ */
727+
633728Handling Arrays
634729---------------
635730
0 commit comments