8000 [Serializer] deserialize as a null when inner object cannot be create… · symfony/symfony@2fe9eb1 · GitHub
[go: up one dir, main page]

Skip to content

Commit 2fe9eb1

Browse files
Jakub Kisielewskifabpot
Jakub Kisielewski
authored andcommitted
[Serializer] deserialize as a null when inner object cannot be created and type hint allows null
1 parent 3ef76bf commit 2fe9eb1

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/Symfony/Component/Serializer/Normalizer/AbstractNormalizer.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -351,6 +351,11 @@ protected function instantiateObject(array &$data, $class, array &$context, \Ref
351351
}
352352
} catch (\ReflectionException $e) {
353353
throw new RuntimeException(sprintf('Could not determine the class of the parameter "%s".', $key), 0, $e);
354+
} catch (MissingConstructorArgumentsException $e) {
355+
if (!$constructorParameter->getType()->allowsNull()) {
356+
throw $e;
357+
}
358+
$parameterData = null;
354359
}
355360

356361
// Don't run set for a parameter passed to the constructor

src/Symfony/Component/Serializer/Tests/Normalizer/ObjectNormalizerTest.php

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,23 @@ public function testConstructorWithObjectTypeHintDenormalize()
182182
$this->assertEquals('rab', $obj->getInner()->bar);
183183
}
184184

185+
public function testConstructorWithUnconstructableNullableObjectTypeHintDenormalize()
186+
{
187+
$data = array(
188+
'id' => 10,
189+
'inner' => null,
190+
);
191+
192+
$normalizer = new ObjectNormalizer();
193+
$serializer = new Serializer(array($normalizer));
194+
$normalizer->setSerializer($serializer);
195+
196+
$obj = $normalizer->denormalize($data, DummyWithNullableConstructorObject::class);
197+
$this->assertInstanceOf(DummyWithNullableConstructorObject::class, $obj);
198+
$this->assertEquals(10, $obj->getId());
199+
$this->assertNull($obj->getInner());
200+
}
201+
185202
/**
186203
* @expectedException \Symfony\Component\Serializer\Exception\RuntimeException
187204
* @expectedExceptionMessage Could not determine the class of the parameter "unknown".
@@ -1109,3 +1126,25 @@ public function getFoo()
11091126
return $this->Foo;
11101127
}
11111128
}
1129+
1130+
class DummyWithNullableConstructorObject
1131+
{
1132+
private $id;
1133+
private $inner;
1134+
1135+
public function __construct($id, ?ObjectConstructorDummy $inner)
1136+
{
1137+
$this->id = $id;
1138+
$this->inner = $inner;
1139+
}
1140+
1141+
public function getId()
1142+
{
1143+
return $this->id;
1144+
}
1145+
1146+
public function getInner()
1147+
{
1148+
return $this->inner;
1149+
}
1150+
}

0 commit comments

Comments
 (0)
0