Skip to content

Commit

Permalink
take into account the context when preserving empty array objects
Browse files Browse the repository at this point in the history
  • Loading branch information
xabbuh committed Jun 1, 2020
1 parent f2d8270 commit a91ceee
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\NotEncodableValueException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareDenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\ContextAwareNormalizerInterface;
Expand Down Expand Up @@ -157,7 +158,7 @@ public function normalize($data, $format = null, array $context = [])
}

if (\is_array($data) || $data instanceof \Traversable) {
if ($data instanceof \Countable && 0 === $data->count()) {
if (($context[AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS] ?? false) === true && $data instanceof \Countable && 0 === $data->count()) {
return $data;
}

Expand Down
21 changes: 21 additions & 0 deletions Tests/SerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -491,6 +491,27 @@ public function testNotNormalizableValueExceptionMessageForAResource()
(new Serializer())->normalize(tmpfile());
}

public function testNormalizeTransformEmptyArrayObjectToArray()
{
$serializer = new Serializer(
[
new PropertyNormalizer(),
new ObjectNormalizer(),
new ArrayDenormalizer(),
],
[
'json' => new JsonEncoder(),
]
);

$object = [];
$object['foo'] = new \ArrayObject();
$object['bar'] = new \ArrayObject(['notempty']);
$object['baz'] = new \ArrayObject(['nested' => new \ArrayObject()]);

$this->assertSame('{"foo":[],"bar":["notempty"],"baz":{"nested":[]}}', $serializer->serialize($object, 'json'));
}

public function testNormalizePreserveEmptyArrayObject()
{
$serializer = new Serializer(
Expand Down

0 comments on commit a91ceee

Please sign in to comment.