[Serializer] Fix serializer tries to denormalize null values on nullable properties

This commit is contained in:
Maxime Steinhausser 2018-05-26 11:34:32 +02:00
parent 6fc7fdb182
commit ca314889e7
3 changed files with 50 additions and 0 deletions

View File

@ -349,6 +349,12 @@ abstract class AbstractNormalizer extends SerializerAwareNormalizer implements N
}
} elseif ($allowed && !$ignored && (isset($data[$key]) || array_key_exists($key, $data))) {
$parameterData = $data[$key];
if (null === $parameterData && $constructorParameter->allowsNull()) {
$params[] = null;
// Don't run set for a parameter passed to the constructor
unset($data[$key]);
continue;
}
try {
if (null !== $constructorParameter->getClass()) {
if (!$this->serializer instanceof DenormalizerInterface) {

View File

@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Serializer\Tests\Fixtures;
class NullableConstructorArgumentDummy
{
private $foo;
public function __construct(?\stdClass $foo)
{
$this->foo = $foo;
}
public function setFoo($foo)
{
$this->foo = 'this setter should not be called when using the constructor argument';
}
public function getFoo()
{
return $this->foo;
}
}

View File

@ -9,6 +9,7 @@ use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Tests\Fixtures\AbstractNormalizerDummy;
use Symfony\Component\Serializer\Tests\Fixtures\NullableConstructorArgumentDummy;
use Symfony\Component\Serializer\Tests\Fixtures\ProxyDummy;
use Symfony\Component\Serializer\Tests\Fixtures\StaticConstructorDummy;
use Symfony\Component\Serializer\Tests\Fixtures\StaticConstructorNormalizer;
@ -116,4 +117,15 @@ class AbstractNormalizerTest extends TestCase
$this->assertEquals('baz', $dummy->quz);
$this->assertNull($dummy->foo);
}
/**
* @requires PHP 7.1
*/
public function testObjectWithNullableConstructorArgument()
{
$normalizer = new ObjectNormalizer();
$dummy = $normalizer->denormalize(array('foo' => null), NullableConstructorArgumentDummy::class);
$this->assertNull($dummy->getFoo());
}
}