Skip to content

Commit 84a1e0a

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 b042dfb commit 84a1e0a

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

components/serializer.rst

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -638,7 +638,7 @@ When serializing, you can set a callback to format a specific object property::
638638
$encoder = new JsonEncoder();
639639

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

@@ -660,6 +660,26 @@ When serializing, you can set a callback to format a specific object property::
660660
$serializer->serialize($person, 'json');
661661
// Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"}
662662

663+
Also, you can pass an \ArrayObject or its subclass to callbacks context field to get more flexibility::
664+
665+
$defaultContext = [
666+
AbstractNormalizer::CALLBACKS => new class extends \ArrayObject {
667+
public function offsetExists($index)
668+
{
669+
return true;
670+
}
671+
672+
public function offsetGet($index)
673+
{
674+
return function () use ($index) {
675+
return $index;
676+
};
677+
}
678+
}
679+
];
680+
681+
$normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext);
682+
663683
.. _component-serializer-normalizers:
664684

665685
Normalizers

0 commit comments

Comments
 (0)