Skip to content

Commit 4182634

Browse files
committed
[Serializer] Documentation about new feature: callbacks context field now can be an \ArrayObject
Also, fixed a typo in basic example of usage callbacks
1 parent 80ba67a commit 4182634

File tree

1 file changed

+22
-2
lines changed

1 file changed

+22
-2
lines changed

components/serializer.rst

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -655,7 +655,7 @@ When serializing, you can set a callback to format a specific object property::
655655
$encoder = new JsonEncoder();
656656

657657
// all callback parameters are optional (you can omit the ones you don't use)
658-
$callback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
658+
$dateCallback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) {
659659
return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : '';
660660
};
661661

@@ -664,7 +664,7 @@ When serializing, you can set a callback to format a specific object property::
664664
'createdAt' => $dateCallback,
665665
],
666666
];
667-
667+
668668
$normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);
669669

670670
$serializer = new Serializer([$normalizer], [$encoder]);
@@ -677,6 +677,26 @@ When serializing, you can set a callback to format a specific object property::
677677
$serializer->serialize($person, 'json');
678678
// Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}
679679

680+
Also, you can pass an \ArrayObject or its subclass to callbacks context field to get more flexibility::
681+
682+
$defaultContext = [
683+
AbstractNormalizer::CALLBACKS => new class() extends \ArrayObject {
684+
public function offsetExists($index)
685+
{
686+
return true;
687+
}
688+
689+
public function offsetGet($index)
690+
{
691+
return function () use ($index) {
692+
return $index;
693+
};
694+
}
695+
}
696+
];
697+
698+
$normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);
699+
680700
.. deprecated:: 4.2
681701

682702
The :method:`Symfony\\Component\\Serializer\\Normalizer\\AbstractNormalizer::setCallbacks` is deprecated since

0 commit comments

Comments
 (0)