Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature: skip empty arrays on serialization #31

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Normalizer/AbstractObjectNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)) {
Expand Down