8000 [Serializer] deserialize as a null when inner object cannot be created and type hint allows null by kbkk · Pull Request #26140 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -351,6 +351,11 @@ protected function instantiateObject(array &$data, $class, array &$context, \Ref
}
} 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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,23 @@ public function testConstructorWithObjectTypeHintDenormalize()
$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".
Expand Down Expand Up @@ -1109,3 +1126,25 @@ public function getFoo()
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;
}
}
0