Skip to content

Commit

Permalink
bug #37049 [Serializer] take into account the context when preserving…
Browse files Browse the repository at this point in the history
… empty array objects (xabbuh)

This PR was merged into the 4.4 branch.

Discussion
----------

[Serializer] take into account the context when preserving empty array objects

| Q             | A
| ------------- | ---
| Branch?       | 4.4
| Bug fix?      | yes
| New feature?  | no
| Deprecations? | no
| Tickets       | Fix #37041
| License       | MIT
| Doc PR        |

Commits
-------

98fff21 take into account the context when preserving empty array objects
  • Loading branch information
fabpot committed Jun 2, 2020
2 parents d87b666 + 98fff21 commit a2f4342
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
3 changes: 2 additions & 1 deletion src/Symfony/Component/Serializer/Serializer.php
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 src/Symfony/Component/Serializer/Tests/SerializerTest.php
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 a2f4342

Please sign in to comment.