8000 [Serializer] Add support for preserving empty object in object property · symfony/symfony@3cff073 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3cff073

Browse files
committed
[Serializer] Add support for preserving empty object in object property
1 parent cbe1f81 commit 3cff073

File tree

3 files changed

+9
-1
lines changed

3 files changed

+9
-1
lines changed

src/Symfony/Component/Serializer/CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ CHANGELOG
55
---
66

77
* Add support of PHP backed enumerations
8+
* Add support for preserving empty object in object property
89

910
5.3
1011
---

src/Symfony/Component/Serializer/Normalizer/AbstractObjectNormalizer.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,10 @@ private function updateData(array $data, string $attribute, $attributeValue, str
592592
return $data;
593593
}
594594

595+
if ([] === $attributeValue && ($context[self::PRESERVE_EMPTY_OBJECTS] ?? $this->defaultContext[self::PRESERVE_EMPTY_OBJECTS] ?? false)) {
596+
$attributeValue = new \ArrayObject();
597+
}
598+
595599
if ($this->nameConverter) {
596600
$attribute = $this->nameConverter->normalize($attribute, $class, $format, $context);
597601
}

src/Symfony/Component/Serializer/Tests/SerializerTest.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -535,7 +535,10 @@ public function testNormalizePreserveEmptyArrayObject()
535535
$object['foo'] = new \ArrayObject();
536536
$object['bar'] = new \ArrayObject(['notempty']);
537537
$object['baz'] = new \ArrayObject(['nested' => new \ArrayObject()]);
538-
$this->assertEquals('{"foo":{},"bar":["notempty"],"baz":{"nested":{}}}', $serializer->serialize($object, 'json', [AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true]));
538+
$object['innerObject'] = new class() {
539+
public array $map = [];
540+
};
541+
$this->assertEquals('{"foo":{},"bar":["notempty"],"baz":{"nested":{}},"innerObject":{"map":{}}}', $serializer->serialize($object, 'json', [AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true]));
539542
}
540543

541544
public function testNormalizeScalar()

0 commit comments

Comments
 (0)
0