From 4182634e09aa9e8dbaaa0819a1b2a00227ef9c04 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9B=D0=B0=D0=B2=D1=80=D0=B8=D0=BD=D0=B5=D0=BD=D0=BA?= =?UTF-8?q?=D0=BE=20=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC?= Date: Fri, 9 Aug 2019 18:38:20 +0300 Subject: [PATCH] [Serializer] Documentation about new feature: callbacks context field now can be an \ArrayObject Also, fixed a typo in basic example of usage callbacks --- components/serializer.rst | 24 ++++++++++++++++++++++-- 1 file changed, 22 insertions(+), 2 deletions(-) diff --git a/components/serializer.rst b/components/serializer.rst index c7d5200d5f5..62632f9bd45 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -655,7 +655,7 @@ When serializing, you can set a callback to format a specific object property:: $encoder = new JsonEncoder(); // all callback parameters are optional (you can omit the ones you don't use) - $callback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) { + $dateCallback = function ($innerObject, $outerObject, string $attributeName, string $format = null, array $context = []) { return $innerObject instanceof \DateTime ? $innerObject->format(\DateTime::ISO8601) : ''; }; @@ -664,7 +664,7 @@ When serializing, you can set a callback to format a specific object property:: 'createdAt' => $dateCallback, ], ]; - + $normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext); $serializer = new Serializer([$normalizer], [$encoder]); @@ -677,6 +677,26 @@ When serializing, you can set a callback to format a specific object property:: $serializer->serialize($person, 'json'); // Output: {"name":"cordoval", "age": 34, "createdAt": "2014-03-22T09:43:12-0500"} +Also, you can pass an \ArrayObject or its subclass to callbacks context field to get more flexibility:: + + $defaultContext = [ + AbstractNormalizer::CALLBACKS => new class() extends \ArrayObject { + public function offsetExists($index) + { + return true; + } + + public function offsetGet($index) + { + return function () use ($index) { + return $index; + }; + } + } + ]; + + $normalizer = new GetSetMethodNormalizer(null, null, null, null, null, $defaultContext); + .. deprecated:: 4.2 The :method:`Symfony\\Component\\Serializer\\Normalizer\\AbstractNormalizer::setCallbacks` is deprecated since