8000 [Serializer] Fix deserialization of object with private constructor by l3l0 · Pull Request #19025 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Serializer] Fix deserialization of object with private constructor #19025

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 @@ -316,6 +316,10 @@ protected function instantiateObject(array &$data, $class, array &$context, \Ref
return $object;
}

if (!$reflectionClass->isInstantiable()) {
return $reflectionClass->newInstanceWithoutConstructor();
}

$constructor = $reflectionClass->getConstructor();
if ($constructor) {
$constructorParameters = $constructor->getParameters();
Expand Down
56 changes: 56 additions & 0 deletions src/Symfony/Component/Serializer/Tests/SerializerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,14 @@ public function testDeserialize()
$this->assertEquals($data, $result->toArray());
}

public function testDeserializeObjectWithPrivateConstructor()
{
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
$data = array('title' => 'foo', 'numbers' => array(5, 3));
$result = $serializer->deserialize(json_encode($data), '\Symfony\Component\Serializer\Tests\ModelWithPrivateConstructor', 'json');
$this->assertEquals($data, $result->toArray());
}

public function testDeserializeUseCache()
{
$serializer = new Serializer(array(new GetSetMethodNormalizer()), array('json' => new JsonEncoder()));
Expand Down Expand Up @@ -309,3 +317,51 @@ public function toArray()
return array('title' => $this->title, 'numbers' => $this->numbers);
}
}

class ModelWithPrivateConstructor
{
private $title;
private $numbers;

private function __construct()
{
}

public static function fromArray($array)
{
$model = new self();
if (isset($array['title'])) {
$model->setTitle($array['title']);
}
if (isset($array['numbers'])) {
$model->setNumbers($array['numbers']);
}

return $model;
}

public function getTitle()
{
return $this->title;
}

public function setTitle($title)
{
$this->title = $title;
}

public function getNumbers()
{
return $this->numbers;
}

public function setNumbers($numbers)
{
$this->numbers = $numbers;
}

public function toArray()
{
return array('title' => $this->title, 'numbers' => $this->numbers);
}
}
0