bug #37049 [Serializer] take into account the context when preserving 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
-------

98fff21140 take into account the context when preserving empty array objects
This commit is contained in:
Fabien Potencier 2020-06-02 10:39:56 +02:00
commit a2f4342d08
2 changed files with 23 additions and 1 deletions

View File

@ -20,6 +20,7 @@ use Symfony\Component\Serializer\Encoder\EncoderInterface;
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;
@ -157,7 +158,7 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface
}
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;
}

View File

@ -491,6 +491,27 @@ class SerializerTest extends TestCase
(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(