Skip to content

Commit

Permalink
[Serializer] Fix denormalizing of array with empty body
Browse files Browse the repository at this point in the history
This happens for example with XML empty tags denormalizing to an object array attribute.
  • Loading branch information
alexandre-daubois committed Sep 27, 2021
1 parent a10b610 commit 5cb0dc3
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Normalizer/AbstractObjectNormalizer.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Exception\ExtraAttributesException;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
Expand Down Expand Up @@ -411,6 +412,10 @@ private function validateAndDenormalize(string $currentClass, string $attribute,
$data = [$data];
}

if (XmlEncoder::FORMAT === $format && '' === $data && Type::BUILTIN_TYPE_ARRAY === $type->getBuiltinType()) {
return [];
}

if (null !== $collectionValueType && Type::BUILTIN_TYPE_OBJECT === $collectionValueType->getBuiltinType()) {
$builtinType = Type::BUILTIN_TYPE_OBJECT;
$class = $collectionValueType->getClassName().'[]';
Expand Down
3 changes: 3 additions & 0 deletions Tests/Normalizer/Features/ObjectDummy.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@
class ObjectDummy
{
protected $foo;
/**
* @var array
*/
public $bar;
private $baz;
protected $camelCase;
Expand Down
13 changes: 13 additions & 0 deletions Tests/Normalizer/ObjectNormalizerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,19 @@ public function testDenormalize()
$this->assertTrue($obj->isBaz());
}

public function testDenormalizeEmptyXmlArray()
{
$normalizer = $this->getDenormalizerForObjectToPopulate();
$obj = $normalizer->denormalize(
['bar' => ''],
ObjectDummy::class,
'xml'
);

$this->assertIsArray($obj->bar);
$this->assertEmpty($obj->bar);
}

public function testDenormalizeWithObject()
{
$data = new \stdClass();
Expand Down

0 comments on commit 5cb0dc3

Please sign in to comment.