Skip to content

Commit

Permalink
feature #28363 [Serializer] Encode empty objects as objects, not arra…
Browse files Browse the repository at this point in the history
…ys (mcfedr)

This PR was merged into the 4.4 branch.

Discussion
----------

[Serializer] Encode empty objects as objects, not arrays

Allows Normalizers to return a representation of an empty object that the encoder recognizes as such.

Often PHP code is relaxed about the difference betweens arrays and objects, and particularly empty arrays are ambiguous. This preserves objects that would otherwise have turned into arrays as objects in the encoding.

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | No
| Deprecations? | No
| Tests pass?   | yes
| Fixed tickets | #23019
| License       | MIT
| Doc PR        | I'll do it if/when this might be merged

Commits
-------

f28e826 [Serializer] Encode empty objects as objects, not arrays
  • Loading branch information
fabpot committed Aug 13, 2019
2 parents 046aff2 + f28e826 commit 44f6e94
Show file tree
Hide file tree
Showing 10 changed files with 109 additions and 5 deletions.
8 changes: 4 additions & 4 deletions src/Symfony/Component/Serializer/Encoder/CsvEncoder.php
Expand Up @@ -69,7 +69,7 @@ public function encode($data, $format, array $context = [])
{
$handle = fopen('php://temp,', 'w+');

if (!\is_array($data)) {
if (!is_iterable($data)) {
$data = [[$data]];
} elseif (empty($data)) {
$data = [[]];
Expand Down Expand Up @@ -210,10 +210,10 @@ public function supportsDecoding($format)
/**
* Flattens an array and generates keys including the path.
*/
private function flatten(array $array, array &$result, string $keySeparator, string $parentKey = '', bool $escapeFormulas = false)
private function flatten(iterable $array, array &$result, string $keySeparator, string $parentKey = '', bool $escapeFormulas = false)
{
foreach ($array as $key => $value) {
if (\is_array($value)) {
if (is_iterable($value)) {
$this->flatten($value, $result, $keySeparator, $parentKey.$key.$keySeparator, $escapeFormulas);
} else {
if ($escapeFormulas && \in_array(substr((string) $value, 0, 1), $this->formulasStartCharacters, true)) {
Expand Down Expand Up @@ -245,7 +245,7 @@ private function getCsvOptions(array $context): array
/**
* @return string[]
*/
private function extractHeaders(array $data): array
private function extractHeaders(iterable $data): array
{
$headers = [];
$flippedHeaders = [];
Expand Down
7 changes: 7 additions & 0 deletions src/Symfony/Component/Serializer/Encoder/YamlEncoder.php
Expand Up @@ -14,6 +14,7 @@
use Symfony\Component\Serializer\Exception\RuntimeException;
use Symfony\Component\Yaml\Dumper;
use Symfony\Component\Yaml\Parser;
use Symfony\Component\Yaml\Yaml;

/**
* Encodes YAML data.
Expand All @@ -25,6 +26,8 @@ class YamlEncoder implements EncoderInterface, DecoderInterface
const FORMAT = 'yaml';
private const ALTERNATIVE_FORMAT = 'yml';

public const PRESERVE_EMPTY_OBJECTS = 'preserve_empty_objects';

private $dumper;
private $parser;
private $defaultContext = ['yaml_inline' => 0, 'yaml_indent' => 0, 'yaml_flags' => 0];
Expand All @@ -47,6 +50,10 @@ public function encode($data, $format, array $context = [])
{
$context = array_merge($this->defaultContext, $context);

if (isset($context[self::PRESERVE_EMPTY_OBJECTS])) {
$context['yaml_flags'] |= Yaml::DUMP_OBJECT_AS_MAP;
}

return $this->dumper->dump($data, $context['yaml_inline'], $context['yaml_indent'], $context['yaml_flags']);
}

Expand Down
Expand Up @@ -88,6 +88,8 @@ abstract class AbstractObjectNormalizer extends AbstractNormalizer
*/
public const DEEP_OBJECT_TO_POPULATE = 'deep_object_to_populate';

public const PRESERVE_EMPTY_OBJECTS = 'preserve_empty_objects';

private $propertyTypeExtractor;
private $typesCache = [];
private $attributesCache = [];
Expand Down Expand Up @@ -206,6 +208,10 @@ public function normalize($object, $format = null, array $context = [])
$data = $this->updateData($data, $attribute, $this->serializer->normalize($attributeValue, $format, $this->createChildContext($context, $attribute, $format)), $class, $format, $context);
}

if (isset($context[self::PRESERVE_EMPTY_OBJECTS]) && !\count($data)) {
return new \ArrayObject();
}

return $data;
}

Expand Down
Expand Up @@ -30,7 +30,7 @@ interface NormalizerInterface
* @param string $format Format the normalization result will be encoded as
* @param array $context Context options for the normalizer
*
* @return array|string|int|float|bool
* @return array|string|int|float|bool|\ArrayObject \ArrayObject is used to make sure an empty object is encoded as an object not an array
*
* @throws InvalidArgumentException Occurs when the object given is not an attempted type for the normalizer
* @throws CircularReferenceException Occurs when the normalizer detects a circular reference when no circular
Expand Down
37 changes: 37 additions & 0 deletions src/Symfony/Component/Serializer/Tests/Encoder/CsvEncoderTest.php
Expand Up @@ -339,6 +339,43 @@ public function testEncodeWithoutHeader()
]));
}

public function testEncodeArrayObject()
{
$value = new \ArrayObject(['foo' => 'hello', 'bar' => 'hey ho']);

$this->assertEquals(<<<'CSV'
foo,bar
hello,"hey ho"
CSV
, $this->encoder->encode($value, 'csv'));

$value = new \ArrayObject();

$this->assertEquals("\n", $this->encoder->encode($value, 'csv'));
}

public function testEncodeNestedArrayObject()
{
$value = new \ArrayObject(['foo' => new \ArrayObject(['nested' => 'value']), 'bar' => new \ArrayObject(['another' => 'word'])]);

$this->assertEquals(<<<'CSV'
foo.nested,bar.another
value,word
CSV
, $this->encoder->encode($value, 'csv'));
}

public function testEncodeEmptyArrayObject()
{
$value = new \ArrayObject();
$this->assertEquals("\n", $this->encoder->encode($value, 'csv'));

$value = ['foo' => new \ArrayObject()];
$this->assertEquals("\n\n", $this->encoder->encode($value, 'csv'));
}

public function testSupportsDecoding()
{
$this->assertTrue($this->encoder->supportsDecoding('csv'));
Expand Down
Expand Up @@ -46,6 +46,8 @@ public function encodeProvider()
return [
[[], '[]', []],
[[], '{}', ['json_encode_options' => JSON_FORCE_OBJECT]],
[new \ArrayObject(), '{}', []],
[new \ArrayObject(['foo' => 'bar']), '{"foo":"bar"}', []],
];
}

Expand Down
20 changes: 20 additions & 0 deletions src/Symfony/Component/Serializer/Tests/Encoder/XmlEncoderTest.php
Expand Up @@ -48,6 +48,26 @@ public function testEncodeScalar()
$this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
}

public function testEncodeArrayObject()
{
$obj = new \ArrayObject(['foo' => 'bar']);

$expected = '<?xml version="1.0"?>'."\n".
'<response><foo>bar</foo></response>'."\n";

$this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
}

public function testEncodeEmptyArrayObject()
{
$obj = new \ArrayObject();

$expected = '<?xml version="1.0"?>'."\n".
'<response/>'."\n";

$this->assertEquals($expected, $this->encoder->encode($obj, 'xml'));
}

/**
* @group legacy
*/
Expand Down
Expand Up @@ -28,6 +28,8 @@ public function testEncode()

$this->assertEquals('foo', $encoder->encode('foo', 'yaml'));
$this->assertEquals('{ foo: 1 }', $encoder->encode(['foo' => 1], 'yaml'));
$this->assertEquals('null', $encoder->encode(new \ArrayObject(['foo' => 1]), 'yaml'));
$this->assertEquals('{ foo: 1 }', $encoder->encode(new \ArrayObject(['foo' => 1]), 'yaml', ['preserve_empty_objects' => true]));
}

public function testSupportsEncoding()
Expand Down
Expand Up @@ -198,12 +198,25 @@ public function testExtraAttributesException()
'allow_extra_attributes' => false,
]);
}

public function testNormalizeEmptyObject()
{
$normalizer = new AbstractObjectNormalizerDummy();

// This results in objects turning into arrays in some encoders
$normalizedData = $normalizer->normalize(new EmptyDummy());
$this->assertEquals([], $normalizedData);

$normalizedData = $normalizer->normalize(new EmptyDummy(), 'any', ['preserve_empty_objects' => true]);
$this->assertEquals(new \ArrayObject(), $normalizedData);
}
}

class AbstractObjectNormalizerDummy extends AbstractObjectNormalizer
{
protected function extractAttributes($object, $format = null, array $context = [])
{
return [];
}

protected function getAttributeValue($object, $attribute, $format = null, array $context = [])
Expand Down Expand Up @@ -233,6 +246,10 @@ class Dummy
public $baz;
}

class EmptyDummy
{
}

class AbstractObjectNormalizerWithMetadata extends AbstractObjectNormalizer
{
public function __construct()
Expand Down
13 changes: 13 additions & 0 deletions src/Symfony/Component/Serializer/Tests/SerializerTest.php
Expand Up @@ -194,6 +194,19 @@ public function testSerializeArrayOfScalars()
$this->assertEquals(json_encode($data), $result);
}

public function testSerializeEmpty()
{
$serializer = new Serializer([new ObjectNormalizer()], ['json' => new JsonEncoder()]);
$data = ['foo' => new \stdClass()];

//Old buggy behaviour
$result = $serializer->serialize($data, 'json');
$this->assertEquals('{"foo":[]}', $result);

$result = $serializer->serialize($data, 'json', ['preserve_empty_objects' => true]);
$this->assertEquals('{"foo":{}}', $result);
}

public function testSerializeNoEncoder()
{
$this->expectException('Symfony\Component\Serializer\Exception\UnexpectedValueException');
Expand Down

0 comments on commit 44f6e94

Please sign in to comment.