Skip to content

[Serializer] Add support for serializing empty array as object #42297

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 30, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Symfony/Component/Serializer/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ CHANGELOG
---

* Add support of PHP backed enumerations
* Add support for preserving empty object in object property
* Add support for serializing empty array as object

5.3
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,10 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
*/
public const DEEP_OBJECT_TO_POPULATE = 'deep_object_to_populate';

/**
* Flag to control whether an empty object should be kept as an object (in
* JSON: {}) or converted to a list (in JSON: []).
*/
public const PRESERVE_EMPTY_OBJECTS = 'preserve_empty_objects';

private $propertyTypeExtractor;
Expand Down Expand Up @@ -592,10 +596,6 @@ private function updateData(array $data, string $attribute, $attributeValue, str
return $data;
}

if ([] === $attributeValue && ($context[self::PRESERVE_EMPTY_OBJECTS] ?? $this->defaultContext[self::PRESERVE_EMPTY_OBJECTS] ?? false)) {
$attributeValue = new \ArrayObject();
}

if ($this->nameConverter) {
$attribute = $this->nameConverter->normalize($attribute, $class, $format, $context);
}
Expand Down
17 changes: 14 additions & 3 deletions src/Symfony/Component/Serializer/Serializer.php
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,12 @@
*/
class Serializer implements SerializerInterface, ContextAwareNormalizerInterface, ContextAwareDenormalizerInterface, ContextAwareEncoderInterface, ContextAwareDecoderInterface
{
/**
* Flag to control whether an empty array should be transformed to an
* object (in JSON: {}) or to a map (in JSON: []).
*/
public const EMPTY_ARRAYS_AS_OBJECT = 'empty_iterable_as_object';

private const SCALAR_TYPES = [
'int' => true,
'bool' => true,
Expand Down Expand Up @@ -159,8 +165,13 @@ public function normalize($data, string $format = null, array $context = [])
}

if (is_iterable($data)) {
if (($context[AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS] ?? false) === true && $data instanceof \Countable && 0 === $data->count()) {
return $data;
if (is_countable($data) && \count($data) === 0) {
switch (true) {
case ($context[AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS] ?? false) && is_object($data):
return $data;
case ($context[self::EMPTY_ARRAYS_AS_OBJECT] ?? false) && is_array($data):
return new \ArrayObject();
}
}

$normalized = [];
Expand All @@ -179,7 +190,7 @@ public function normalize($data, string $format = null, array $context = [])
throw new NotNormalizableValueException(sprintf('Could not normalize object of type "%s", no supporting normalizer found.', get_debug_type($data)));
}

throw new NotNormalizableValueException('An unexpected value could not be normalized: '.(!\is_resource($data) ? var_export($data, true) : sprintf('%s resource', get_resource_type($data))));
throw new NotNormalizableValueException('An unexpected value could not be normalized: '.(!\is_resource($data) ? var_export($data, true) : sprintf('"%s" resource', get_resource_type($data))));
}

/**
Expand Down
115 changes: 106 additions & 9 deletions src/Symfony/Component/Serializer/Tests/SerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -492,7 +492,7 @@ public function testExceptionWhenTypeIsNotInTheBodyToDeserialiaze()
public function testNotNormalizableValueExceptionMessageForAResource()
{
$this->expectException(NotNormalizableValueException::class);
$this->expectExceptionMessage('An unexpected value could not be normalized: stream resource');
$this->expectExceptionMessage('An unexpected value could not be normalized: "stream" resource');

(new Serializer())->normalize(tmpfile());
}
Expand All @@ -514,11 +514,13 @@ public function testNormalizeTransformEmptyArrayObjectToArray()
$object['foo'] = new \ArrayObject();
$object['bar'] = new \ArrayObject(['notempty']);
$object['baz'] = new \ArrayObject(['nested' => new \ArrayObject()]);
$object['a'] = new \ArrayObject(['nested' => []]);
$object['b'] = [];

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

public function testNormalizePreserveEmptyArrayObject()
public function provideObjectOrCollectionTests()
{
$serializer = new Serializer(
[
Expand All @@ -531,14 +533,77 @@ public function testNormalizePreserveEmptyArrayObject()
]
);

$object = [];
$object['foo'] = new \ArrayObject();
$object['bar'] = new \ArrayObject(['notempty']);
$object['baz'] = new \ArrayObject(['nested' => new \ArrayObject()]);
$object['innerObject'] = new class() {
$data = [];
$data['a1'] = new \ArrayObject();
$data['a2'] = new \ArrayObject(['k' => 'v']);
$data['b1'] = [];
$data['b2'] = ['k' => 'v'];
$data['c1'] = new \ArrayObject(['nested' => new \ArrayObject()]);
$data['c2'] = new \ArrayObject(['nested' => new \ArrayObject(['k' => 'v'])]);
$data['d1'] = new \ArrayObject(['nested' => []]);
$data['d2'] = new \ArrayObject(['nested' => ['k' => 'v']]);
$data['e1'] = new class() {
public $map = [];
};
$this->assertEquals('{"foo":{},"bar":["notempty"],"baz":{"nested":{}},"innerObject":{"map":{}}}', $serializer->serialize($object, 'json', [AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true]));
$data['e2'] = new class() {
public $map = ['k' => 'v'];
};
$data['f1'] = new class(new \ArrayObject()) {
public $map;

public function __construct(\ArrayObject $map)
{
$this->map = $map;
}
};
$data['f2'] = new class(new \ArrayObject(['k' => 'v'])) {
public $map;

public function __construct(\ArrayObject $map)
{
$this->map = $map;
}
};

$data['g1'] = new Baz([]);
$data['g2'] = new Baz(['greg']);

yield [$serializer, $data];
}

/** @dataProvider provideObjectOrCollectionTests */
public function testNormalizeWithCollection(Serializer $serializer, array $data)
{
$expected = '{"a1":[],"a2":{"k":"v"},"b1":[],"b2":{"k":"v"},"c1":{"nested":[]},"c2":{"nested":{"k":"v"}},"d1":{"nested":[]},"d2":{"nested":{"k":"v"}},"e1":{"map":[]},"e2":{"map":{"k":"v"}},"f1":{"map":[]},"f2":{"map":{"k":"v"}},"g1":{"list":[],"settings":[]},"g2":{"list":["greg"],"settings":[]}}';
$this->assertSame($expected, $serializer->serialize($data, 'json'));
}

/** @dataProvider provideObjectOrCollectionTests */
public function testNormalizePreserveEmptyArrayObject(Serializer $serializer, array $data)
{
$expected = '{"a1":{},"a2":{"k":"v"},"b1":[],"b2":{"k":"v"},"c1":{"nested":{}},"c2":{"nested":{"k":"v"}},"d1":{"nested":[]},"d2":{"nested":{"k":"v"}},"e1":{"map":[]},"e2":{"map":{"k":"v"}},"f1":{"map":{}},"f2":{"map":{"k":"v"}},"g1":{"list":{"list":[]},"settings":[]},"g2":{"list":["greg"],"settings":[]}}';
$this->assertSame($expected, $serializer->serialize($data, 'json', [
AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true,
]));
}

/** @dataProvider provideObjectOrCollectionTests */
public function testNormalizeEmptyArrayAsObject(Serializer $serializer, array $data)
{
$expected = '{"a1":[],"a2":{"k":"v"},"b1":{},"b2":{"k":"v"},"c1":{"nested":[]},"c2":{"nested":{"k":"v"}},"d1":{"nested":{}},"d2":{"nested":{"k":"v"}},"e1":{"map":{}},"e2":{"map":{"k":"v"}},"f1":{"map":[]},"f2":{"map":{"k":"v"}},"g1":{"list":[],"settings":{}},"g2":{"list":["greg"],"settings":{}}}';
$this->assertSame($expected, $serializer->serialize($data, 'json', [
Serializer::EMPTY_ARRAYS_AS_OBJECT => true,
]));
}

/** @dataProvider provideObjectOrCollectionTests */
public function testNormalizeEmptyArrayAsObjectAndPreserveEmptyArrayObject(Serializer $serializer, array $data)
{
$expected = '{"a1":{},"a2":{"k":"v"},"b1":{},"b2":{"k":"v"},"c1":{"nested":{}},"c2":{"nested":{"k":"v"}},"d1":{"nested":{}},"d2":{"nested":{"k":"v"}},"e1":{"map":{}},"e2":{"map":{"k":"v"}},"f1":{"map":{}},"f2":{"map":{"k":"v"}},"g1":{"list":{"list":[]},"settings":{}},"g2":{"list":["greg"],"settings":{}}}';
$this->assertSame($expected, $serializer->serialize($data, 'json', [
Serializer::EMPTY_ARRAYS_AS_OBJECT => true,
AbstractObjectNormalizer::PRESERVE_EMPTY_OBJECTS => true,
]));
}

public function testNormalizeScalar()
Expand Down Expand Up @@ -714,6 +779,38 @@ public function __construct($value)
}
}

class Baz
{
public $list;

public $settings = [];

public function __construct(array $list)
{
$this->list = new DummyList($list);
}
}

class DummyList implements \Countable, \IteratorAggregate
{
public $list;

public function __construct(array $list)
{
$this->list = $list;
}

public function count(): int
{
return \count($this->list);
}

public function getIterator():\Traversable
{
return new \ArrayIterator($this->list);
}
}

interface NormalizerAwareNormalizer extends NormalizerInterface, NormalizerAwareInterface
{
}
Expand Down