Fix serializer do not transform empty \Traversable to Array
This commit is contained in:
parent
1bc3ee798d
commit
e5c20293fa
@ -157,6 +157,10 @@ class Serializer implements SerializerInterface, ContextAwareNormalizerInterface
|
||||
}
|
||||
|
||||
if (\is_array($data) || $data instanceof \Traversable) {
|
||||
if ($data instanceof \Countable && 0 === $data->count()) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$normalized = [];
|
||||
foreach ($data as $key => $val) {
|
||||
$normalized[$key] = $this->normalize($val, $format, $context);
|
||||
|
@ -25,6 +25,7 @@ use Symfony\Component\Serializer\Mapping\ClassMetadataInterface;
|
||||
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
|
||||
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
|
||||
use Symfony\Component\Serializer\Mapping\Loader\AnnotationLoader;
|
||||
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
|
||||
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
|
||||
use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
|
||||
use Symfony\Component\Serializer\Normalizer\DenormalizerAwareInterface;
|
||||
@ -490,6 +491,26 @@ class SerializerTest extends TestCase
|
||||
(new Serializer())->normalize(tmpfile());
|
||||
}
|
||||
|
||||
public function testNormalizePreserveEmptyArrayObject()
|
||||
{
|
||||
$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->assertEquals('{"foo":{},"bar":["notempty"],"baz":{"nested":{}}}', $serializer->serialize($object, 'json', [AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true]));
|
||||
}
|
||||
|
||||
private function serializerWithClassDiscriminator()
|
||||
{
|
||||
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
|
||||
|
Reference in New Issue
Block a user