From d0a95968ff0028ca721ad5440e19e596ebbab01e Mon Sep 17 00:00:00 2001 From: vvoody- Date: Thu, 3 Aug 2023 11:52:57 +0200 Subject: [PATCH] Feature: skip empty arrays on serialization --- Normalizer/AbstractObjectNormalizer.php | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Normalizer/AbstractObjectNormalizer.php b/Normalizer/AbstractObjectNormalizer.php index b252d6219..4d3d8a78d 100644 --- a/Normalizer/AbstractObjectNormalizer.php +++ b/Normalizer/AbstractObjectNormalizer.php @@ -61,6 +61,12 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer */ public const SKIP_NULL_VALUES = 'skip_null_values'; + /** + * Flag to control whether fields with the value `[]` should be output + * when normalizing or omitted. + */ + public const SKIP_EMPTY_ARRAY_VALUES = 'skip_empty_array_values'; + /** * Flag to control whether uninitialized PHP>=7.4 typed class properties * should be excluded when normalizing. @@ -654,6 +660,10 @@ private function updateData(array $data, string $attribute, mixed $attributeValu return $data; } + if (is_array($attributeValue) && count($attributeValue) === 0 && ($context[self::SKIP_EMPTY_ARRAY_VALUES] ?? $this->defaultContext[self::SKIP_EMPTY_ARRAY_VALUES] ?? false)) { + return $data; + } + if (null !== $classMetadata && null !== $serializedPath = ($attributesMetadata[$attribute] ?? null)?->getSerializedPath()) { $propertyAccessor = PropertyAccess::createPropertyAccessor(); if ($propertyAccessor->isReadable($data, $serializedPath) && null !== $propertyAccessor->getValue($data, $serializedPath)) {