Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit a4dad43

Browse files
committed
[Serializer] Allow to access to the context and various other infos in callbacks and max depth handler
1 parent 8a88478 commit a4dad43

File tree

1 file changed

+15
-6
lines changed

1 file changed

+15
-6
lines changed

components/serializer.rst

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -545,10 +545,9 @@ When serializing, you can set a callback to format a specific object property::
545545
$encoder = new JsonEncoder();
546546
$normalizer = new GetSetMethodNormalizer();
547547

548-
$callback = function ($dateTime) {
549-
return $dateTime instanceof \DateTime
550-
? $dateTime->format(\DateTime::ISO8601)
551-
: '';
548+
$callback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = null) {
549+
// Every parameters can be omitted if not used
550+
return $dateTime instanceof \DateTime ? $dateTime->format(\DateTime::ISO8601) : '';
552551
};
553552

554553
$normalizer->setCallbacks(array('createdAt' => $callback));
@@ -563,6 +562,11 @@ When serializing, you can set a callback to format a specific object property::
563562
$serializer->serialize($person, 'json');
564563
// Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}
565564

565+
.. versionadded:: 4.2
566+
The ``$outerObject``, ``$attributeName``, ``$format`` and ``$context``
567+
parameters of the callback were introduced in Symfony 4.2.
568+
569+
566570
.. _component-serializer-normalizers:
567571

568572
Normalizers
@@ -964,8 +968,9 @@ having unique identifiers::
964968

965969
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
966970
$normalizer = new ObjectNormalizer($classMetadataFactory);
967-
$normalizer->setMaxDepthHandler(function ($foo) {
968-
return '/foos/'.$foo->id;
971+
$normalizer->setMaxDepthHandler(function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = null) {
972+
// Every parameters can be omitted if not used
973+
return '/foos/'.$innerObject->id;
969974
});
970975

971976
$serializer = new Serializer(array($normalizer));
@@ -984,6 +989,10 @@ having unique identifiers::
984989
.. versionadded:: 4.1
985990
The ``setMaxDepthHandler()`` method was introduced in Symfony 4.1.
986991

992+
.. versionadded:: 4.2
993+
The ``$outerObject``, ``$attributeName``, ``$format`` and ``$context``
994+
parameters of ``setMaxDepthHandler()`` were introduced in Symfony 4.2.
995+
987996
Handling Arrays
988997
---------------
989998

0 commit comments

Comments
 (0)