[Serializer] deserialize as a null when inner object cannot be created and type hint allows null

This commit is contained in:
Jakub Kisielewski 2018-02-11 15:26:58 +01:00 committed by Fabien Potencier
parent 3ef76bfc0b
commit 2fe9eb1aba
2 changed files with 44 additions and 0 deletions

View File

@ -351,6 +351,11 @@ abstract class AbstractNormalizer implements NormalizerInterface, DenormalizerIn
}
} catch (\ReflectionException $e) {
throw new RuntimeException(sprintf('Could not determine the class of the parameter "%s".', $key), 0, $e);
} catch (MissingConstructorArgumentsException $e) {
if (!$constructorParameter->getType()->allowsNull()) {
throw $e;
}
$parameterData = null;
}
// Don't run set for a parameter passed to the constructor

View File

@ -182,6 +182,23 @@ class ObjectNormalizerTest extends TestCase
$this->assertEquals('rab', $obj->getInner()->bar);
}
public function testConstructorWithUnconstructableNullableObjectTypeHintDenormalize()
{
$data = array(
'id' => 10,
'inner' => null,
);
$normalizer = new ObjectNormalizer();
$serializer = new Serializer(array($normalizer));
$normalizer->setSerializer($serializer);
$obj = $normalizer->denormalize($data, DummyWithNullableConstructorObject::class);
$this->assertInstanceOf(DummyWithNullableConstructorObject::class, $obj);
$this->assertEquals(10, $obj->getId());
$this->assertNull($obj->getInner());
}
/**
* @expectedException \Symfony\Component\Serializer\Exception\RuntimeException
* @expectedExceptionMessage Could not determine the class of the parameter "unknown".
@ -1109,3 +1126,25 @@ class ObjectWithUpperCaseAttributeNames
return $this->Foo;
}
}
class DummyWithNullableConstructorObject
{
private $id;
private $inner;
public function __construct($id, ?ObjectConstructorDummy $inner)
{
$this->id = $id;
$this->inner = $inner;
}
public function getId()
{
return $this->id;
}
public function getInner()
{
return $this->inner;
}
}