From 3ff28ab8293cc0d3e17d20f3349d5d47eaf7b2fd Mon Sep 17 00:00:00 2001 From: NorthBlue333 Date: Sun, 12 Jun 2022 22:25:02 +0200 Subject: [PATCH] Add COLLECT_EXTRA_ATTRIBUTES_ERRORS doc --- components/serializer.rst | 33 +++++++++++++++++++++++++++++++-- 1 file changed, 31 insertions(+), 2 deletions(-) diff --git a/components/serializer.rst b/components/serializer.rst index 706d2f492a4..01b1c530514 100644 --- a/components/serializer.rst +++ b/components/serializer.rst @@ -195,6 +195,11 @@ when constructing the normalizer:: AbstractNormalizer::ALLOW_EXTRA_ATTRIBUTES => false, ]); +.. tip:: + + If your object contains nested objects, an ``ExtraAttributesException`` will be thrown at first nested object containing + extra attributes. When this happens, you can use :ref:`Attributes Groups section ` + Deserializing in an Existing Object ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -1266,8 +1271,8 @@ Collecting Type Errors While Denormalizing ------------------------------------------ When denormalizing a payload to an object with typed properties, you'll get an -exception if the payload contains properties that don't have the same type as -the object. +exception ``NotNormalizableValueException`` if the payload contains properties that don't have the same type as +the object, at first incorrect type. In those situations, use the ``COLLECT_DENORMALIZATION_ERRORS`` option to collect all exceptions at once, and to get the object partially denormalized:: @@ -1291,6 +1296,30 @@ collect all exceptions at once, and to get the object partially denormalized:: return $this->json($violations, 400); } +Collecting Extra Attributes Errors While Denormalizing +------------------------------------------ + +When denormalizing a payload with ``ALLOW_EXTRA_ATTRIBUTES`` set to false to an object with nested objects, you'll get an +exception at first ``ExtraAttributesException`` in nested objects. + +In those situations, use the ``COLLECT_EXTRA_ATTRIBUTES_ERRORS`` option to +collect all exceptions at once, and to get the object partially denormalized:: + + try { + $dto = $serializer->deserialize($request->getContent(), MyDto::class, 'json', [ + DenormalizerInterface::COLLECT_EXTRA_ATTRIBUTES_ERRORS => true, + ]); + } catch (PartialDenormalizationException $e) { + $violations = new ConstraintViolationList(); + if (null !== $extraAttributesException = $e->getExtraAttributesError()) { + foreach ($extraAttributesException->getExtraAttributes() as $extraAttribute) { + $violations->add(new ConstraintViolation('This attribute is not allowed.', '', [], null, $extraAttribute, null)); + }; + } + + return $this->json($violations, 400); + } + Handling Circular References ----------------------------